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

发布于 2024-08-29 05:05:01 字数 438 浏览 3 评论 0原文

考虑以下代码:

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。但函数签名隐藏了可变声明。

如何声明指向可变成员的指针来编译此代码? 如果不可能,请链接到标准 C++。

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

Compiler generates an error message. The thing is that the member m is mutable therefore it is allowed to change m. But the function signature hides mutable declaration.

How to decalre pointer-to-mutable-member to compile this code?
If it is impossible please link to Standard C++.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

红墙和绿瓦 2024-09-05 05:05:01

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

简历资格的限制,
以及以何种方式
操作数的 cv 限定符是
组合起来产生简历限定符
的结果,与
E1.E2 的规则在 5.2.5 中给出。 [笔记:
不可能使用指向可变成员的指针
成员修改 const 类
对象。

例如,

<前><代码>结构S {
可变 int i;
};
常量 S cs;
int S::* pm = &S::i; // pm 引用可变成员 S::i
cs.*pm = 88; // 格式错误:cs 是 const 对象

]

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

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

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

This code is ill-formed according to C++ Standard 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

]

You could use wrapper class to workaround this problem as follows:

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

But I think you should consider redesign your code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文