Is there a way to identify the const modifier of the variable in run-time?

c++, rtti

Solution

If you're using C++11 you don't need rtti at all, you can use std::is_const example :

int x1 = 0;
const int x2 = 0;
bool is_x1_const = std::is_const<decltype(x1)>::value;
bool is_x2_const = std::is_const<decltype(x2)>::value;

Old C++ version :

template<typename T> bool is_const(T) { return false;}
template<typename T> bool is_const(const T) { return true;}

Problem

What I mean is the following question. Then I try to know the type and the constancy of the `const` pointer using `typeinfo` library, we get them both: ``` int* pY1 = 0; const int* pY2 = 0; std::cout << "pY1: " << typeid(pY1).name() << std::endl; std::cout << "pY2: " << typeid(pY2).name() << std::endl; ``` Output: ``` pY1: int * pY2: int const * ``` But then I try the following ``` int x1 = 0; const int x2 = 0; std::cout << " x1: " << typeid(x1).name() << std::endl; std::cout << " x2: " << typeid(x2).name() << std::endl; ``` an output is ``` x1: int x2: int ``` ideone code Is it possible to recognise the constant in the runtime? If yes, how to do this?

Original source