3

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)?

Martin Perry
  • 9,232
  • 8
  • 46
  • 114

1 Answers1

3

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);
}
Henri Menke
  • 10,705
  • 1
  • 24
  • 42
  • Shouldn't there be void in return typename inside class definition as well? – Martin Perry Apr 29 '17 at 10:25
  • @MatrinPerry I'm sorry, I missed that. It works nevertheless because `void` is the default. If the return type was something else, e.g. `int`, it would have broken. – Henri Menke Apr 29 '17 at 10:27