Why should I avoid std::enable_if in function signatures

hansmaad picture hansmaad · Jan 30, 2013 · Viewed 37.4k times · Source

Scott Meyers posted content and status of his next book EC++11. He wrote that one item in the book could be "Avoid std::enable_if in function signatures".

std::enable_if can be used as a function argument, as a return type or as a class template or function template parameter to conditionally remove functions or classes from overload resolution.

In this question all three solution are shown.

As function parameter:

template<typename T>
struct Check1
{
   template<typename U = T>
   U read(typename std::enable_if<
          std::is_same<U, int>::value >::type* = 0) { return 42; }

   template<typename U = T>
   U read(typename std::enable_if<
          std::is_same<U, double>::value >::type* = 0) { return 3.14; }   
};

As template parameter:

template<typename T>
struct Check2
{
   template<typename U = T, typename std::enable_if<
            std::is_same<U, int>::value, int>::type = 0>
   U read() { return 42; }

   template<typename U = T, typename std::enable_if<
            std::is_same<U, double>::value, int>::type = 0>
   U read() { return 3.14; }   
};

As return type:

template<typename T>
struct Check3
{
   template<typename U = T>
   typename std::enable_if<std::is_same<U, int>::value, U>::type read() {
      return 42;
   }

   template<typename U = T>
   typename std::enable_if<std::is_same<U, double>::value, U>::type read() {
      return 3.14;
   }   
};
  • Which solution should be preferred and why should I avoid others?
  • In which cases "Avoid std::enable_if in function signatures" concerns usage as return type (which is not part of normal function signature but of template specializations)?
  • Are there any differences for member and non-member function templates?

Answer

R. Martinho Fernandes picture R. Martinho Fernandes · Jan 31, 2013

Put the hack in the template parameters.

The enable_if on template parameter approach has at least two advantages over the others:

  • readability: the enable_if use and the return/argument types are not merged together into one messy chunk of typename disambiguators and nested type accesses; even though the clutter of the disambiguator and nested type can be mitigated with alias templates, that would still merge two unrelated things together. The enable_if use is related to the template parameters not to the return types. Having them in the template parameters means they are closer to what matters;

  • universal applicability: constructors don't have return types, and some operators cannot have extra arguments, so neither of the other two options can be applied everywhere. Putting enable_if in a template parameter works everywhere since you can only use SFINAE on templates anyway.

For me, the readability aspect is the big motivating factor in this choice.