在下一个示例中,如何避免为 Volatile 和非 Volatile bar++;
方法编写相同的正文(foo
)?
#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();
}
这个问题完全是How do I remove code duplication between similar const and non-const member functions?的类比,但是由于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?
是。
How to avoid writing the same body (bar++;) for volatile and non-volatile foo methods in the next example?
据我所知,具有非静态成员函数的唯一选择是将函数主体放入类似函数的宏中。
最好使用非成员(或静态成员)功能模板代替:
template<class AA>
void foo(AA& a) { a.bar++; }
这不需要重复,并且可以用
volatile
或non-volatile
对象调用。
关于c++ - 避免对 volatile 和非 volatile 成员函数进行代码重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59603808/