Game Development by Sean

C++11 Usage of std::enable_if in Function Templates

Table of Contents

This is just a quick post for those of you who don’t already know about this.

In C++11, function templates can now have default template argument, e.g.

template <typename Type1, typename Type2 = void>
void foo();

foo<int>(); // Type1=int, Type2=void
foo<float, char>(); // Type1=float, Type2=char</code>

Previously this was only available for class templates.

The nice thing is that this can be applied with std::enable_if, just like with class templates before. Where as we previously had to do some kind of monstrosity like:

template <typename Type>
typename std::enable_if<condition<Type>::value, return_type>::type foo(const Type&);

We can now do the slightly cleaner and much friendlier to IDEs version:

template <typename Type, typename std::enable_if<condition<Type>::value, int>::type = 0>
return_type foo(const Type&);

If you aren’t selecting a return type with meta-programming, this is much nicer. IDEs are happier figuring out the return type for you. Tools which document signatures tend to be happier. All around, it’s just better. Expect C++14 to make std::enable_if a little easier to use, too.

C++14 Update

The preferred C++14 syntax makes use of the new type alias feature and std::enable_if_t<Bool> and variable templates like so:

template <typename Type, typename = std::enable_if_t<condition_v<Type>>>
return_type foo(const Type&);

If you aren’t using variable templates (possibly you’re using a compiler that doesn’t yet support them) the use of condition would just stay the same as it was before.