std::enable_if minimal example
Also see std::enable_if and std::is_floating_point minimal example and std::enable_if and std::is_same minimal example
Let’s say you have a template function:
template<typename T>
T mySine(T arg) {
return sin(arg);
}
Now you want to enable this function only if T
is a floating point number (i.e. no integer!). Use std::enable_if like this:
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;
}