I'm trying to optimize out some function at compile time by using an enum class as a template parameter.
Say for example
enum class Color { RED, BLACK };
Now, I would like to define a method
void myMethod<Color c> () {
if( c == Color::RED ) { ... }
if( c == Color::BLACK ) { ... }
}
And I would like the compiler to make 2 copies of myMethod and eliminate the dead code during the optimisation (it's for CUDA kernels so speed and register usage is important to me)
However, seems like when I call the method using
void doSomething( const Color c ) {
myMethod<c>();
}
MSVC complains with "expression must have a constant value".
I was expecting the compiler to be clever enough to compile a version of myMethod with each possible version of the enum. Is that not the case ? Can I force it to, without an ugly switch in doSomething ?
Thanks for your help !
myMethod<Color>()you want to call, if it's dependent of a non-constant variable. So, you are back to aswitch()(or an if-else-cascade, or an array mapping colors to function pointers, or something else).constdoesn't make a (compile time) constant expresion, i.e. a expression that can be evaluated at compile time.ifs out of the most inner loops to the outside. Of course, the nested loops had to be re-implemented for every case. There I used the template-with-value-parameters to prevent code duplication. the template, the call of that template and a little explanation Optimization Attempts.