C ++ 11 - implementation of enable_if function - outside of class definition
How can I implement a function with a template that has enable_if?
class Test
{
public:
Test(){}
~Test(){}
template<typename T, typename std::enable_if<std::is_integral<T>::value>::type>
void do_something(T v);
template<typename T, typename std::enable_if<std::is_floating_point<T>::value>::type>
void do_something(T v);
};
How to implement do_something
for different types outside of the class definition (i.e. in an inline file)?
+3
source to share
1 answer
You are using enable_if
for the return type. This is documented in cppreference :
A common mistake is to declare two function templates that differ only in the default template arguments. This is illegal because the default template arguments are not part of the function template signature, and it is illegal to declare two different function templates with the same signature.
#include <iostream>
#include <type_traits>
class Test
{
public:
Test(){}
~Test(){}
template<typename T>
typename std::enable_if<std::is_integral<T>::value, void>::type
do_something(T v);
template<typename T>
typename std::enable_if<std::is_floating_point<T>::value, void>::type
do_something(T v);
};
template<typename T>
typename std::enable_if<std::is_integral<T>::value, void>::type
Test::do_something(T v) { std::cout << "Integral\n"; }
template<typename T>
typename std::enable_if<std::is_floating_point<T>::value, void>::type
Test::do_something(T v) { std::cout << "Floating point\n"; }
int main()
{
Test t;
t.do_something(1);
t.do_something(3.14);
}
+2
source to share