首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >消除Const:从std::shared_ptr<const T>到T的铸造

消除Const:从std::shared_ptr<const T>到T的铸造
EN

Stack Overflow用户
提问于 2022-04-23 22:17:16
回答 1查看 100关注 0票数 0

请问有从T = std::shared_ptr<const A>TCV = A的转换方式吗?我用这个:

代码语言:javascript
运行
复制
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的签名是:

代码语言:javascript
运行
复制
template<typename A, typename B>
forward_operate(A&, B&);

这个代码不工作(ofc),你能帮忙吗?另外,我是否应该这样做(我需要这样做)?

EN

回答 1

Stack Overflow用户

发布于 2022-04-23 22:48:07

从std::shared_ptr到T的铸造

不能从(智能)指针向指定类型进行转换。您必须通过指针间接访问指定对象。

根据尝试的代码,看起来您正在尝试这样做:

代码语言:javascript
运行
复制
forward_operate(
    const_cast<typename T::element_type&>(*x),
    const_cast<typename U::element_type&>(*y));

请记住,抛弃const是一种强烈的代码气味。除非你明白它的作用,否则不要这样做。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71984022

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档