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

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)?



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1