加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

检查C 03上是否为const

发布时间:2020-12-16 05:56:17 所属栏目:百科 来源:网络整理
导读:如果一个对象是没有C 11的std :: is_const的const,据我所知,我不应该const_casting一个被声明为const的对象 解决方法 C11的is_const的示例实现在 cppreference给出,如下所示: templateclass T struct is_const : false_type {};templateclass T struct is_c
如果一个对象是没有C 11的std :: is_const的const,据我所知,我不应该const_casting一个被声明为const的对象

解决方法

C11的is_const的示例实现在 cppreference给出,如下所示:
template<class T> struct is_const          : false_type {};
template<class T> struct is_const<const T> : true_type {};

如果您将此定义放在C 03代码中,那么也可以使用is_const,如果添加了false_type和true_type的定义(感谢mfonantini指出缺少的true_type和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; }
};

唯一的区别是静态值只是一个const,而不是一个constexpr,但是注意它是一个常量表达式,可以用作模板参数.所以为了所有实际的目的,上面的定义应该在C 03中运行.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读