删除 const:从 std::shared_ptr<const T> 强制转换为 T

Removing Const: Casting from std::shared_ptr<const T> to T

提问人:Vero 提问时间:4/24/2022 最后编辑:Vero 更新时间:4/24/2022 访问量:225

问:

有没有办法从请到请?我用了这个: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),您能帮忙吗?我也应该这样做吗(我需要这样做)?

C++(英语:C++) 模板 铸造 常数 常播

评论

0赞 Vero 4/24/2022
真是太可惜了。谢谢!
0赞 Paul Sanders 4/24/2022
这真是太可惜了为什么?你为什么对演员如此着迷?
0赞 Vero 4/24/2022
因为我在代码上添加了太多约束:)我想成为唯一的演员,并且用户有 const 的东西!否则,我可能不得不参加设计模式课程。
0赞 Paul Sanders 4/24/2022
好吧,我不明白你在这里想做什么,但如果用户符合某些条件,她可能有理由......const

答:

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 是一种强烈的代码气味。除非您了解它的作用,否则不要这样做。