是否有一种方法可以在运行时识别变量的const修饰符

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

本文关键字:变量 识别 运行时 const 方法 一种 是否      更新时间:2023-10-16

我的意思是以下问题。然后,我尝试使用typeinfo库知道const指针的类型和恒定,我们得到了两个:

int* pY1 = 0;
const int* pY2 = 0;
std::cout << "pY1: " << typeid(pY1).name() << std::endl;
std::cout << "pY2: " << typeid(pY2).name() << std::endl;

输出:

pY1: int *
pY2: int const *

,但是我尝试以下

int x1 = 0;
const int x2 = 0;   
std::cout << " x1: " << typeid(x1).name() << std::endl;
std::cout << " x2: " << typeid(x2).name() << std::endl;

输出是

x1: int
x2: int

IDEONE代码
是否可以识别运行时的常数?如果是,该怎么做?

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

旧的C 版本:

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

请访问地址,您又回到了工作案例:

int x1 = 0;
const int x2 = 0;
std::cout << " x1: " << typeid(&x1).name( ) << std::endl;
std::cout << " x2: " << typeid(&x2).name( ) << std::endl;

在运行时没有constness的概念。这是仅在编译时使用的东西,这给您带来比您预期更早了解constness的好处。

如果您没有可用于std::is_const的C 11,则仍然可以复制实现并通过模板专业化来推导constness。有关示例实现

template<class T> struct is_const          : std::false_type {};
template<class T> struct is_const<const T> : std::true_type {};

您也可以使用函数而不是类型做类似的操作,但是您会失去逻辑的编译时间。