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?
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;}
Take the address, and you are back to your working case:
int x1 = 0;
const int x2 = 0;
std::cout << " x1: " << typeid(&x1).name( ) << std::endl;
std::cout << " x2: " << typeid(&x2).name( ) << std::endl;
At runtime there is no concept of constness. This is something that is used only at compile-time, which gives you the benefit of knowing constness earlier than you envision it.
If you don't have C++11 available for std::is_const
, you can still copy an implementation and deduce constness with template specialization. See http://en.cppreference.com/w/cpp/types/is_const for an example implementation.
template<class T> struct is_const : std::false_type {};
template<class T> struct is_const<const T> : std::true_type {};
You could do something similar with a function instead of a type as well, but you lose the compile-time aspect of the logic.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.