Consider a function template func
that is very performance critical. It can be instantiated with T=Type1
or some other type. Part of the function logic depends on T
it is instantiated with.
One can either explicitly use a if constexpr
(Code B) or use a vanilla if
instead (Code A), while compiler probably optimizes the code.
However, I wonder, how the implementation without constexpr
(Code A) is any different? Isn't the compiler capable of detecting which branch of if
(in Code A) to use at compile time while instantiating? Can it still (for Code A) generate a less efficient code?
Code A. Without if constexpr
:
template<class T>
void func(T argument)
{
// some general type-independent logic
if (std::is_same<Type1,T>::value)
{
// do something
}
else
{
// do something else
}
// some general type-independent logic
}
Code B. With if constexpr
:
template<class T>
void func(T argument)
{
// some general type-independent logic
if constexpr (std::is_same<Type1,T>::value)
{
// do something
}
else
{
// do something else
}
// some general type-independent logic
}
Both codes A & B compile, as do something
and do something else
are well-formed for any T
.
There are some similar-sounding questions:
- Why is
constexpr if
needed? – this one answers whenconstexpr
is required. - Difference between
if
andconstexpr if
– just lists the differences
The aforementioned questions do not answer if Code B is preferable to Code A for some reason (when both branches are well-formed anyway).
The only advantage I see would be to tell the programmer explicitly that this if
is compile-time; however, I would say the conditional expression is self-explanatory.