std::enable_if and std::is_same minimal example
Also see std::enable_if minimal example and std::enable_if and std::is_floating_point minimal example
Example for a template function that is only enabled if the template argument T
is a double
using std::enable_if
and std::is_same
:
template<typename T, typename std::enable_if<std::is_same<T, double>::value>::type* = nullptr>
T mySineDoubleOnly(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_same<T, double>::value>::type* = nullptr>
T mySineDoubleOnly(T arg) {
return sin(arg);
}
int main() {
cout << mySine(1.5) << endl;
// mySine(1) will work
// mySineDoubleOnly(1) will fail to compile
cout << mySineDoubleOnly(1.5) << endl;
}