Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select the method at compilation time?

Tags:

c++

templates

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.
}
like image 482
user1899020 Avatar asked Dec 08 '22 12:12

user1899020


2 Answers

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>());
}
like image 96
Mankarse Avatar answered Dec 24 '22 15:12

Mankarse


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
}
like image 36
Dietmar Kühl Avatar answered Dec 24 '22 14:12

Dietmar Kühl