提问人:Vero 提问时间:4/24/2022 最后编辑:Vero 更新时间:4/24/2022 访问量:225
删除 const:从 std::shared_ptr<const T> 强制转换为 T
Removing Const: Casting from std::shared_ptr<const T> to T
问:
有没有办法从请到请?我用了这个:T = std::shared_ptr<const A>
TCV = A
template<typename T> struct is_shared_ptr : std::false_type {};
template<typename T> struct is_shared_ptr<std::shared_ptr<T>> : std::true_type {};
template<typename T>
concept is_shared = is_shared_ptr<T>::value;
template<typename T, typename U>
requires is_shared<T> and is_shared<U>
static void operate(const T& x, const U& y)
{
using TCV = std::remove_cv<typename decltype(T)::element_value>;
using UCV = std::remove_cv<typename decltype(U)::element_value>;
forward_operate(const_cast<TCV>(*x), const_cast<UCV>(*y));
};
签名是:forward_operate
template<typename A, typename B>
forward_operate(A&, B&);
此代码不起作用(ofc),您能帮忙吗?我也应该这样做吗(我需要这样做)?
答:
0赞
eerorika
4/24/2022
#1
从 std::shared_ptr 到 T 的强制转换
不能从(智能)指针强制转换为尖头类型。必须通过指针间接访问指向的对象。
根据尝试的代码,看起来您正在尝试执行此操作:
forward_operate(
const_cast<typename T::element_type&>(*x),
const_cast<typename U::element_type&>(*y));
请记住,抛弃 const 是一种强烈的代码气味。除非您了解它的作用,否则不要这样做。
评论
const