I remember reading some article using new C++ features to implement the selection at compiler time but cannot figure out how to do it. For example, I have a method doing the following
template<class T>
void foo()
{
if (std::is_abstract<T>::value)
do something;
else
do others.
}
Compile time decision making is usually done through overload selection.
void foo_impl(std::true_type) {
do something;
}
void foo_impl(std::false_type) {
do others.
}
template<class T>
void foo()
{
foo_impl(std::is_abstract<T>());
}
If both of your branches compile, the above code is actually OK and will do the selection at compile time: there will be one branch the compiler will detect as being dead and never use. When optimizing no self-respecting compiler will use a branch.
Especially when the branches may not compile depending on the type, you could use std::enable_if
to conditionally make overloads available:
template <typename T>
typename std::enable_if<std::is_abstract<T>::value>::type foo()
{
do something
}
template <typename T>
typename std::enable_if<!std::is_abstract<T>::value>::type foo()
{
do other
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With