检查对象是否声明为const [英] Check if object declared const

查看:135
本文介绍了检查对象是否声明为const的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果对象被声明为const,我想打破编译。

I would like to break the compilation if the object is declared const.

以下不工作:

#include <type_traits>

struct A {

    A() : v(0)
    {
        static_assert( ! std::is_const<decltype(*this)>::value, "declared as const" );
    }

    int& AccessValue() const
    {
        return const_cast< int& >( v );
    }

    int v;
};

int main()
{
    A a1; // ok, this compiles
    const A a2; // no, this break the compilation

    a1.AccessValue() = 5; // ok
    a2.AccessValue() = 6; // OPS
}

因此,有一种方法可以打破编译

So, is there a way to break the compilation if an object of this type is declared const?

推荐答案

这个的类型纯粹是由你使用它的方法的签名来决定的。也就是说,这个总是类型 cv T * const 其中 cv 对应于方法的CV限定符。

The type of this is purely dictacted by the signature of the method in which you use it. That is, this is always of type cv T* const where cv corresponds to the CV qualifiers of the method.

因此,在构造函数中, this code> T * const 。

Therefore, in a constructor, this is just T* const.

const_cast 是一个代码气味,通常只在使用 const - 破坏传统库...或(有时),以避免违反DRY。在新代码中,您不必使用它。

const_cast is a code smell, normally only of use when dealing with const-broken legacy libraries... or (sometimes) to avoid violating DRY. In new code, you should not have to use it.

您可以选择:


  • make AccessValue 非常数,因为它不是

  • 声明 i mutable

  • make AccessValue non-const, since it is not
  • declare i as being mutable.

我建议选择前解决方案。给予私有属性的句柄已经是坏的(破坏封装),不需要违反 const 正确性。

I would advise choosing the former solution. Giving away a handle to a private attribute is bad already (breaks encapsulation), no need to violate const correctness as well.

这篇关于检查对象是否声明为const的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆