是否有一种方法可以在运行时识别变量的const修饰符
Is there a way to identify the const modifier of the variable in run-time?
我的意思是以下问题。然后,我尝试使用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 {};
您也可以使用函数而不是类型做类似的操作,但是您会失去逻辑的编译时间。
相关文章:
- 家庭作业问题 - C++更新已识别的变量
- 如何修复 Typedef 变量未识别错误 C++ (Visual Studio 2017)
- 识别矩阵变量分配的行为
- 为什么我的程序无法识别结构中的变量?
- 在无法识别的条件中初始化的局部变量
- Visual Studio environmant 变量未被 C++ stdlib getenv 识别
- While 循环的变量未被识别为已初始化
- C++基本变量识别
- 声明cudaError_t变量时出现无法识别的令牌错误
- 如何在不运行的情况下识别LUA脚本中的非初始化变量
- 您如何使用字符串或字符在C 中识别名称识别变量
- 是否有一种方法可以在运行时识别变量的const修饰符
- 识别给定函数中的不同变量
- 如何识别变量的类型
- 除了更改环境变量"PATH"之外,您还需要做什么才能让 Eclipse 识别 MinGW?
- 有人可以指出为什么我的变量无法识别以及为什么我不能重载我的运算符吗
- 识别和执行变量
- 在Mac OSX Yosemite上,编译器无法识别父类成员变量(Apple LLVM 7.0)
- 视觉C++无法识别 OpenCV 变量
- 混合 C/C++ 源,无法识别链接上的"外部"变量