How to create a pointer-to-mutable-member?

Consider the following code:

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

The compiler generates an error message. The fact is that the member has been mchanged, so he is allowed to change m. But the signature of the function hides the volatile declaration.

How to declare a pointer to-mutable-member to compile this code? If this is not possible, refer to the C ++ standard.

+5
source share
1 answer

This code is poorly formed in accordance with the C ++ 5.5 / 5 standard:

cv-, , cv- cv- , , E1.E2, 5.2.5. [: , const .,

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

, .

+8

All Articles