删除const:从std :: shared_ptr< const t&gt铸造。到t

发布于 2025-01-23 16:22:01 字数 941 浏览 3 评论 0原文

有没有一种方法可以从t = std :: shared_ptr< const a> to 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),请您提供帮助吗?我也应该这样做(我需要这样做)吗?

Is there a way to cast from T = std::shared_ptr<const A> to TCV = A please? I used this:

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));
};

signature of forward_operate is:

template<typename A, typename B>
forward_operate(A&, B&);

This code doesn't work (ofc), could you please help? Also should I ever do this ever (I need to do this)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不如归去 2025-01-30 16:22:02

从std :: shared_ptr到t

铸造

您无法从(智能)指针铸造到尖头类型。您必须通过指针间接访问指向对象。

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

forward_operate(
    const_cast<typename T::element_type&>(*x),
    const_cast<typename U::element_type&>(*y));

请记住,抛弃const是强烈的代码气味。除非您了解它的作用,否则不要这样做。

Casting from std::shared_ptr to T

You cannot cast from a (smart) pointer to the pointed type. You must indirect through the pointer to access the pointed object.

Based on the attempted code, looks like you're trying to do this:

forward_operate(
    const_cast<typename T::element_type&>(*x),
    const_cast<typename U::element_type&>(*y));

Do keep in mind that casting away const is a strong code smell. Don't do this unless you understand what it does.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文