Mohit Mohit - 3 months ago 18
C++ Question

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

Answer

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*");