c++ - 如何创建指向可变成员的指针?

标签 c++ templates constants mutable pointer-to-member

考虑以下代码:

struct Foo
{
    mutable int m;

    template<int Foo::* member> 
    void change_member() const {
        this->*member = 12; // Error: you cannot assign to a variable that is const
    }

    void g() const {
    change_member<&Foo::m>();
    }
};

编译器生成一条错误消息。问题是成员 m 是可变的,因此允许更改 m。但是函数签名隐藏了可变声明。

如何对指向可变成员的指针进行 decalre 以编译这段代码? 如果不可能,请链接到标准 C++。

最佳答案

根据 C++ 标准 5.5/5,此代码格式错误:

The restrictions on cv-qualification, and the manner in which the cv-qualifiers of the operands are combined to produce the cv-qualifiers of the result, are the same as the rules for E1.E2 given in 5.2.5. [Note: it is not possible to use a pointer to member that refers to a mutable member to modify a const class object. For example,

struct S {
  mutable int i;
};
const S cs;
int S::* pm = &S::i; // pm refers to mutable member S::i
cs.*pm = 88;         // ill-formed: cs is a const object

]

您可以使用包装类来解决此问题,如下所示:

template<typename T> struct mutable_wrapper { mutable T value; };

struct Foo
{
    mutable_wrapper<int> m;

    template<mutable_wrapper<int> Foo::* member> 
    void change_member() const {
        (this->*member).value = 12; // no error
    }

    void g() const {
    change_member<&Foo::m>();
    }
};

但我认为您应该考虑重新设计代码。

关于c++ - 如何创建指向可变成员的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2675228/

相关文章:

c++ - 接受 char* 的模板化函数

c - 将 int 和 const int 转换为 float 时的不同结果

android - 使用 native CocosDenshion、cocos2d-x 循环播放音效时,AudioFlinger 无法创建音轨,状态为 : -12 ,

c++ - 设计延迟加载

c++ - Mat 二值图像的最佳访问像素值方法?

C++,FFMpeg : Unable to find any decoder or encoder

c++ - C++ 中派生类的模板参数的运行时选择 - 标准名称?

c++ - OpenCV 模板匹配相似对象

java - JAVA中如何根据环境动态选择配置?

c++ - const 变量是否放置在只读内存中?