0

I want to have code included in a function based on a compile time constant value, but static_if is not a construct in C++.

So I can write functions like this

class TA {
public:
    template<bool flag>
    void func() {
        if(flag)
            a++;
    }

    int a;
};


int main() {
    TA a;
    a.func<true>();
    a.func<false>();
}

And I want to have a guarantee that the compiler makes two functions. One where 'if(flag) a++' is compiled into the function and one where it is not.

Is it possible to get this guarantee based on the C++17 standard, or am I at the mercy of the compiler vendor?

Thanks.

Generic Name
  • 1,083
  • 1
  • 12
  • 19
  • Template instantiations are always separate functions. Are you worried that `TA::func` will contain but always skip the `a++` code? – aschepler Oct 30 '17 at 11:43
  • Optimization should take care of that, but if you really worry about it you can specialize the template, and overwrite it for each boolean value (true, false) since it is only two, it is doable. But again... sounds like premature optimization, which you shouldn't do. – Tommy Andersen Oct 30 '17 at 11:45

1 Answers1

3

In actual fact, C++17 does include exactly what you're asking about - it's callled if constexpr.

You can use it anywhere your condition can be evaluated at compile time (such as template instantiation):

class TA {
public:
    template<bool flag>
    void func() {
        if constexpr (flag)
            a++;
    }

    int a;
};

However, as others have said, in this example you're unlikely to gain much as the compiler can often optimize stuff like this.

Steve
  • 1,747
  • 10
  • 18
  • `if constexpr`? Nice! – Timo Oct 30 '17 at 11:50
  • @Timo Yep! You can also use `constexpr` when declaring variables (from C++11 onwards), and do stuff like `constexpr bool c = true; a.func ();` - without the `constexpr` that would fail as `c` wouldn't be known at compile time. – Steve Oct 30 '17 at 12:06
  • Yeah I already knew that. But the if statement was new to me. And I really like that feature. – Timo Oct 30 '17 at 12:47
  • I second the 'Nice!' comment. This is exactly what I need. – Generic Name Oct 31 '17 at 15:01