Reputation: 37
I have this template function -
template <int N>
void foo() {
if (N < 2) {
bar1();
} else {
bar2();
}
}
I want to deduce if else during compile time in C++11 to make the function efficient. I thought of adding an additional template bool variable like this -
template <int N, bool I = (N < 2), std::enable_if<I>>
void foo() {
bar1();
}
template <int N, bool I = (N < 2), std::enable_if<!I>>
void foo() {
bar2();
}
Not sure if this is the right approach. Can anyone please help?
Upvotes: 0
Views: 1032
Reputation: 60208
In C++11, you can use enable_if
to write 2 overloads
template <int N, typename std::enable_if<N < 2, int*>::type = nullptr>
void foo() {
bar1();
}
template <int N, typename std::enable_if<N >= 2, int*>::type = nullptr>
void foo() {
bar2();
}
Here's a demo
Note that this is unlikely to give you any performance advantage. Compilers will be able to use the template parameter N
in the if
condition to remove the unneeded branch.
Upvotes: 2