Reputation:
How to avoid writing the same body (bar++;
) for volatile and non-volatile foo
methods in the next example?
#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?
Upvotes: 1
Views: 128
Reputation: 238401
if apply the same answer for volatile, wouldn't it be inefficient for non-volatile uses because volatile can make code slower?
Yes.
How to avoid writing the same body (bar++;) for volatile and non-volatile foo methods in the next example?
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.
Upvotes: 1
Reputation: 38072
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.
Upvotes: 0