[英]Avoid code duplication for volatile and non-volatile member function
How to avoid writing the same body ( bar++;
) for volatile and non-volatile foo
methods in the next example?如何避免在下一个示例中为 volatile 和非 volatile
foo
方法编写相同的主体( bar++;
)?
#include <iostream>
struct A {
int bar = 0;
void foo() { bar++; }
void foo() volatile { bar++; }
};
int main() {
A a;
a.foo();
volatile A va;
va.foo();
}
This question is a complete analog of How do I remove code duplication between similar const and non-const member functions?这个问题完全模拟了如何删除类似的常量和非常量成员函数之间的代码重复? , but since const and non-const versions don't affect compiler optimizations, I am wondering: if apply the same answer for volatile, wouldn't it be inefficient for non-volatile uses because volatile can make code slower?
,但由于 const 和非 const 版本不影响编译器优化,我想知道:如果对 volatile 应用相同的答案,那么非 volatile 使用会不会效率低下,因为 volatile 会使代码变慢?
if apply the same answer for volatile, wouldn't it be inefficient for non-volatile uses because volatile can make code slower?
如果对 volatile 应用相同的答案,那么对于非 volatile 用途是否效率低下,因为 volatile 会使代码变慢?
Yes.是的。
How to avoid writing the same body (bar++;) for volatile and non-volatile foo methods in the next example?
如何避免在下一个示例中为 volatile 和非 volatile foo 方法编写相同的主体 (bar++;)?
As far as I can tell, the only option with a non-static member function is to put the function body into a function-like macro.据我所知,非静态成员函数的唯一选择是将函数体放入类似函数的宏中。
It might be preferable to use a non-member (or static member) function template instead:最好使用非成员(或静态成员)函数模板来代替:
template<class AA>
void foo(AA& a) { a.bar++; }
This requires no repetition and can be invoked with either volatile
or non- volatile
object.这不需要重复并且可以使用
volatile
或非易失volatile
对象调用。
Since volatile method can be called for none volatile objects simply trash none volatile method.由于可以为非易失性对象调用易失性方法,因此只需删除非易失性方法即可。
Anyway volatile
has little usage see this topic , so do not make your code to complex and do not use this keyword if you do not have a really good reason to do it.无论如何
volatile
很少使用,请参阅此主题,因此如果您没有真正好的理由,请不要使您的代码变得复杂并且不要使用此关键字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.