9

如何检查一个对象是否是没有 C++11 的 const std::is_const?据我所知,我不应该是const_cast一个被声明为const的对象

4

1 回答 1

12

在cppreferenceis_const上给出了 C++11 的示例实现,它看起来像这样:

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

如果你把这个定义放在你的 C++03 代码中,你也可以is_const在那里使用,如果你为false_typeand添加定义true_type(感谢 mfonantini 指出缺少的true_typeand false_type)。如果您将它们定义如下,您将非常接近 C++11 中使用的定义:

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; }
};

唯一的区别是 staticvalue只是一个const,而不是constexpr,但请注意,它仍然是一个常量表达式,可以用作模板参数。因此,出于所有实际目的,上面的定义应该在 C++03 中有效。

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

于 2012-11-20T03:33:19.143 回答