简体   繁体   English

有没有办法在运行时识别变量的const修饰符?

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

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: 然后我尝试使用typeinfo库知道const指针的类型和const ,我们得到它们:

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 : 如果您使用的是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;

Old C++ version : 旧C ++版本:

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. 在运行时,没有constness的概念。 This is something that is used only at compile-time, which gives you the benefit of knowing constness earlier than you envision it. 这是仅在编译时使用的东西,它为您提供了比您想象的更早了解constness的好处。

If you don't have C++11 available for std::is_const , you can still copy an implementation and deduce constness with template specialization. 如果没有可用于std::is_const C ++ 11,您仍然可以复制实现并使用模板特化来推导std::is_const See http://en.cppreference.com/w/cpp/types/is_const for an example implementation. 有关示例实现,请参见http://en.cppreference.com/w/cpp/types/is_const

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. 您可以使用函数而不是类型执行类似的操作,但是您将失去逻辑的编译时方面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM