Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/125.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 检查C+上是否为常量+;03_C++_C++03 - Fatal编程技术网

C++ 检查C+上是否为常量+;03

C++ 检查C+上是否为常量+;03,c++,c++03,C++,C++03,如果没有C++11的std::is_const,如何检查对象是否为常量?据我所知,我不应该对已声明的对象进行const\u cast template<class T> struct is_const : false_type {}; template<class T> struct is_const<const T> : true_type {}; 唯一的区别是静态的值仅仅是一个常量,而不是常量表达式,但是请注意,它是一个常量表达式,可以

如果没有C++11的
std::is_const
,如何检查对象是否为常量?据我所知,我不应该对已声明的对象进行
const\u cast

template<class T> struct is_const          : false_type {};
template<class T> struct is_const<const T> : true_type {};
唯一的区别是静态的
仅仅是一个
常量
,而不是
常量表达式
,但是请注意,它是一个常量表达式,可以用作模板参数。因此,出于所有实际目的,上面的定义应该适用于C++03


关于问题的最后一部分:将非常量类型转换为常量实际上没有问题。(但是,指向指针的指针或指向指针的引用可能会出现非法情况,例如,
T**
不能转换为
const T**

根据本节的限制,可以使用const\u cast运算符将表达式转换为自己的类型。-5.2.11/2你实际上误解了你应该做什么和不应该做什么。您不应该丢弃最初声明为
const
的对象的常量。也就是说,您不能使用
is_const
(C++11或您自己的)来检测这一点,因为这将只处理您拥有的引用类型,它可能比实际对象更符合const条件。注意:对象const(ness)是在编译时定义的。这不是运行时功能。因此,术语
检查对象是否为const
实际上不是正确的术语。您可以根据模板参数const(ness)生成不同的代码,但这是编译时特性。注意:强制转换(包括const_cast)是一个运行时活动,不是编译时。@LokiAstari:我不确定我是否遵循了。只有
dynamic\u cast
具有运行时行为,其他所有行为都只是编译时类型转换。@GManNickG:措辞糟糕。这是一个应用于运行时对象的操作。
std::true/false\u type
是C++11的一个功能。@mfontani是的,我没有想到这一点。我已在答案中添加了必要的变通方法。谢谢
struct true_type {
  static const bool value = true;
  typedef bool value_type;
  typedef true_type type;
  operator value_type() const { return value; }
};

struct false_type {
  static const bool value = false;
  typedef bool value_type;
  typedef false_type type;
  operator value_type() const { return value; }
};