Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Consider function template<typename T> void Fun(T t);. How can I have different implementations of it for integral and floating types respectively?

I guess building blocks are std::enable_if, std::is_integral, std::is_floating_point. But I cannot put them together in an elegant way :-( .

P.S. I got C++11 available.

like image 408
updogliu Avatar asked Feb 13 '23 17:02

updogliu


1 Answers

See the example code for std::enable_if on cppreference.com.

EDIT:

Adapted the code from the link above as follows:

#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 of enable_if is template< bool B, class T = void > struct enable_if;. This gives the following options for return value 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
like image 164
TAS Avatar answered Feb 16 '23 08:02

TAS