How can I implement function with template that have 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 the class definition (i.e. in inline file)?
You use enable_if on the return type. This is described on cppreference:
A common mistake is to declare two function templates that differ only in their default template arguments. This is illegal because default template arguments are not part of function template's signature, and declaring two different function templates with the same signature is illegal.
#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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With