Also see std::enable_if minimal example and std::enable_if and std::is_same minimal example
Example for a template function that is only enabled if the template argument T
is any floating point number type using std::enable_if
and std::is_floating_point
:
template<typename T, typename std::enable_if<std::is_floating_point<T>::value>::type* = nullptr> T mySineFloatingPointOnly(T arg) { return sin(arg); }
Full example:
#include <iostream> #include <type_traits> #include <cmath> using std::cout; using std::endl; template<typename T> T mySine(T arg) { return sin(arg); } template<typename T, typename std::enable_if<std::is_floating_point<T>::value>::type* = nullptr> T mySineFloatingPointOnly(T arg) { return sin(arg); } int main() { cout << mySine(1.5) << endl; // mySine(1) will work // mySineFloatingPointOnly(1) will fail to compile cout << mySineFloatingPointOnly(1.5) << endl; }