1

Consider the following piece of code with a conditional signature of the function foo based on a constexpr flag. This flag is also checked before calling the function in order to guarantee that the correct function is called.

constexpr bool flag = true;

template <bool enabled>
struct MyStruct {
    int foo(int x) { return x * 2; }
};

template<>
struct MyStruct<false> {
    int foo(int x, int y) { return x + y; }
};

int main() {
    MyStruct<flag> my_struct;
    if constexpr (flag) {
        return my_struct.foo(5);
    } else {
        return my_struct.foo(3, 4);
    }
}

godbolt link as well. Currently as written the code fails to compile because the else branch contains a call to foo that does not exist because it was compiled away. Is there no way to do this? My program effectively has two modes that I'd like to be able to switch between at compile time with two slightly different APIs. Is this even possible?

This relates this other question asked a while ago but I'm not sure if there's some work-around that exists now. I understand that this doesn't exactly work as written but is there some way to accomplish the same thing?

Keltek
  • 460
  • 3
  • 14

0 Answers0