Reputation: 4662
Suppose we have a templated function in which a tiny part of code is dependent on the template parameter type. From design POV(or from any POV for that matter), which one is better! Using if else check on the parameter type by using type_traits
(we could use is_same
) or template specialization(We can put that tiny part in another function which we can specialize) ?
template <typename T>
void func(T log) {
// common part
// part dependent on T. We can put this in a separate function which we can specialize.
// or we can do:
// if (std::is_same<T, type1>::value) {
// //code1;
// } else if (std::is_same<T, type2>::value) {
// //code2;
// } else {
// //generic code;
// }
// common part
}
Upvotes: 0
Views: 1490
Reputation: 25623
Using the run time if
is a bad idea, because everything is already known to compile time. That exactly is the reason why c++ introduced constexpr if
for that case you mention. constexpr if
needs a c++17 compliant compiler, which should be the case in 2018 :-)
template <typename T>
void func(T ) {
std::cout << "common before" << std::endl;
if constexpr (std::is_same<T, int>::value) {
std::cout << "int" << std::endl;
} else if constexpr (std::is_same<T, double>::value) {
std::cout << "double" << std::endl;
} else {
std::cout << "other" << std::endl;
}
std::cout << "common after" << std::endl;
}
int main()
{
func(1);
func(1.1);
func('a');
}
But there is a point you should mention: If you have a big "common" part in your templated function, doesn't matter if you template specialization or constexpr if
, you get a full copy of that code for every template instance. So it is a good idea to move that code to a function, to get the common part only once. If the compiler sees that inlining that code is a good choice, it will do it and you get the best of both solutions.
Upvotes: 2