我的意思是以下问题.然后我尝试const使用typeinfo库知道指针的类型和常量,我们得到它们:
int* pY1 = 0;
const int* pY2 = 0;
std::cout << "pY1: " << typeid(pY1).name() << std::endl;
std::cout << "pY2: " << typeid(pY2).name() << std::endl;
Run Code Online (Sandbox Code Playgroud)
输出:
pY1: int *
pY2: int const *
Run Code Online (Sandbox Code Playgroud)
但后来我尝试以下方法
int x1 = 0;
const int x2 = 0;
std::cout << " x1: " << typeid(x1).name() << std::endl;
std::cout << " x2: " << typeid(x2).name() << std::endl;
Run Code Online (Sandbox Code Playgroud)
输出是
x1: int
x2: int
Run Code Online (Sandbox Code Playgroud)
ideone代码
是否可以识别运行时中的常量?如果是的话,怎么做?
One*_*One 10
如果您使用的是C++ 11,则根本不需要rtti,您可以使用std :: is_const示例:
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;
Run Code Online (Sandbox Code Playgroud)
旧C++版本:
template<typename T> bool is_const(T) { return false;}
template<typename T> bool is_const(const T) { return true;}
Run Code Online (Sandbox Code Playgroud)