Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How do I make this static_assert pass in my failing code? I tried all permutations of const around T but I am not able to get const int *. 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);
}
like image 391
Mohit Avatar asked Feb 07 '23 09:02

Mohit


1 Answers

You could use std::conditional to handle pointer types correctly.

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*");
like image 102
Praetorian Avatar answered Feb 24 '23 10:02

Praetorian