C++避免常量和非常量访问的代码重复
我有一个类应该为每个成员变量调用访问者方法。像这样的事情:
class A{
int a, b, c;
public:
void accept(Visitor &visitor){
visitor.visit(a);
visitor.visit(b);
visitor.visit(c);
}
};
如何在不重复代码的情况下使用相同的代码获得 void accept() const
方法?
重复的明显解决方案是添加一个方法:
void accept(Visitor &visitor) const {
visitor.visit(a);
visitor.visit(b);
visitor.visit(c);
}
该方法具有我想要的确切含义,但我想避免代码重复。使用这两种方法的原因是能够通过“读取”访问者读取变量,并很好地使用 accept
方法 const
。然后非常量 accept
将可以用于“写入/更新”访问者。
I have a class that should call a visitor method for every member variable. Something like this:
class A{
int a, b, c;
public:
void accept(Visitor &visitor){
visitor.visit(a);
visitor.visit(b);
visitor.visit(c);
}
};
How can I get void accept() const
method with the same code without code duplication?
The obvious solution with the duplication is to add a method:
void accept(Visitor &visitor) const {
visitor.visit(a);
visitor.visit(b);
visitor.visit(c);
}
That method has exactly the meaning I want, but I would like to avoid the code duplication. The reason to have both methods is to be able to read the variables by a 'reading' visitor and having the accept
method nicely const
. Then the non-const accept
would be possible to use for 'writing/updating' visitors.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以创建一个类静态模板辅助函数,该函数将根据您提供给它的
this
指针的类型推断出常量性。像这样:You could create a class static template helper function that will deduce the constness based on the type of the
this
pointer you provide to it. Like this:模板助手:
Template helper: