← Samples

Class template SFINAE

123456789101112#include <type_traits> template <typename T, typename Enable = void> class foo; template <typename T> class foo<T, typename std::enable_if<std::is_integral<T>::value>::type> { }; template <typename T> class foo<T, typename std::enable_if<std::is_floating_point<T>::value>::type> { };

This sample is licensed under the CC0 Public Domain Dedication.


Conditionally instantiate a class template depending on the template arguments.


We provide two partial specializations of the foo class template:

  1. The template on lines 6–8 will only be instantiated when T is an integral type.
  2. The template on lines 10–12 will only be instantiated when T is a floating point type.

This allows us to provide different implementations of the foo class depending on the template arguments it is instantiated with.

We have used std::enable_if on line 7 and line 11 to force instantiation to succeed only for the appropriate template arguments. This relies on Substitution Failure Is Not An Error (SFINAE), which states that failing to instantiate a template with some particular template arguments does not result in an error and simply discards that instantiation.

If you want to simply prevent a template from being instantiated for certain template arguments, consider using static_assert instead.


  • Alejandro Mallea
  • Joseph Mansfield

Last Updated

09 April 2015


Fork this sample on GitHub