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?