Mohit Mohit - 1 year ago 78
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

pass in my failing code? I tried all permutations of
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 Source

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

using CT = typename std::conditional<
                typename std::remove_pointer<T>::type const *,
                T const
static_assert(std::is_same<CT,const int *>::value, "CT is not const int*");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download