How to specialize the template function for integral and floating types, respectively?

Consider the function template<typename T> void Fun(T t);. How can I implement various implementations for integral and floating types?

I think that the building blocks are std::enable_if, std::is_integral, std::is_floating_point. But I can’t assemble them in an elegant style :-(.

PS I got C ++ 11.

+4
source share
1 answer

See the std :: enable_if example code at cppreference.com .

EDIT:

Adapted code from the link above:

#include <type_traits>
#include <iostream>


template<class T>
typename std::enable_if<std::is_integral<T>::value>::type foo(T t) 
{
    std::cout << "is integral" << std::endl;
}

template<class T>
typename std::enable_if<std::is_floating_point<T>::value>::type foo(T t) 
{
    std::cout << "is real" << std::endl;
}

int main()
{
    foo(1); 
    foo(1.0);
}

The definition enable_ifis template< bool B, class T = void > struct enable_if;. This gives the following parameters for the return type:

template<class T>
typename std::enable_if<std::is_integral<T>::value>::type foo(T t) // void return type

template<class T>
typename std::enable_if<std::is_integral<T>::value, T>::type foo(T t) // return type from template parameter

template<class T>
typename std::enable_if<std::is_integral<T>::value, size_t>::type foo(T t) // fixed return type
+7

All Articles