How to apply a lower level const to a template variable. I am trying to write a const_cast implementation

How do I make this static_assertpass in my failed code? I tried all the permutations constaround T, but I can’t get it const int *. The compiler always interprets it as int * const.

template <class T>
union const_cast_impl {

    using CT =  const T;
    static_assert(std::is_same<CT,const int *>::value, "CT is not const int*");

    T data;
    CT cdata;

    const_cast_impl(CT ptr):cdata(ptr){}

    operator T(){
        return data;
    }
};

int main(){
    int a = 2;
    const int *ptr = &a;
    int *ptr2 = const_cast_impl<int *>(ptr);
}
+4
source share
2 answers

You can use std::conditionalfor the proper handling of pointer types.

using CT = typename std::conditional<
                std::is_pointer<T>::value,
                typename std::remove_pointer<T>::type const *,
                T const
            >::type;
static_assert(std::is_same<CT,const int *>::value, "CT is not const int*");
+6
source

Just for completeness, you can write a character that is specialized for pointers:

template <class T> struct const_qualify     { using type = T const; };
template <class T> struct const_qualify<T*> { using type = T const*; };
template <class T> struct const_qualify<T&> { using type = T const&; };

And then:

using CT = typename const_qualify<T>::type;

, , .

+2

Source: https://habr.com/ru/post/1650849/


All Articles