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

C++ 有没有办法在运行时识别变量的const修饰符?,c++,rtti,C++,Rtti,我的意思是下面的问题。 然后我尝试使用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; 但是我尝试了以下方法

我的意思是下面的问题。 然后我尝试使用
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;
但是我尝试了以下方法

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


是否可以在运行时识别该常量?如果是,怎么做

记下地址,您就回到您的工作案例:

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

std::cout如果您使用的是C++11,您根本不需要rtti,您可以使用以下示例:

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;
intx1=0;
常数int x2=0;
布尔是常数=标准::是常数::值;
bool是_x2_const=std::is_const::value;

旧C++版本:

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

在运行时没有常数的概念。这是只在编译时使用的东西,它使您能够比预想的更早地了解常量

如果您没有可用于
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 {};
模板结构是_const:std::false_type{};
模板结构是_const:std::true_type{};

您也可以使用函数而不是类型来执行类似的操作,但会丢失逻辑的编译时方面。

不幸的是,我现在不使用C++11。但是无论如何,谢谢你。它可以在C++ 03中容易实现。但是代码却不能。使用函数会丢失编译时间的东西,但是它仍然比使用RTTI快。一个旧的C++版本的决策看起来像个黑客,但它是如此的优雅:谢谢!RTTI是运行时类型信息;但在编译时,您已经拥有了所有信息,这些信息是以静态类型的变量编码的。
template<typename T> bool is_const(T) { return false;}
template<typename T> bool is_const(const T) { return true;}
template<class T> struct is_const          : std::false_type {};
template<class T> struct is_const<const T> : std::true_type {};