Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 - enable_if - function implementation outside of class definition

Tags:

c++

c++11

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

like image 267
Martin Perry Avatar asked Dec 04 '25 09:12

Martin Perry


1 Answers

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);
}
like image 66
Henri Menke Avatar answered Dec 06 '25 22:12

Henri Menke