Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ template for numeric types

I want to have a template to select on numeric types, but I want to also have a global type template too. I tried to apply the solution for this question, but it didn't work:

template<typename T, typename ... Types>
void myFct(T arg1, Types ... rest) { /*do stuff*/ }

template<typename T, typename = typename std::enable_if<std::is_arithmetic<T>::value, T>::type, 
                     typename ... Types>
void myFct(T arg1, Types ... rest) { /* do stuff */ }

because now I have two functions with the same header. What's the right way to do something like:

template<typename T, typename ... Types>
void myFct(T arg1, Types ... rest) 
{ 
    if (isNumeric(T))
        doNumericStuff();
    else
        doStuff();
}
like image 788
Northik Avatar asked Jan 08 '23 08:01

Northik


1 Answers

There's probably better ways of doing this, but the simplest way to me is to just slap the enable_if onto the return type:

template<typename T, typename ... Types>
typename std::enable_if<
    std::is_arithmetic<T>::value
>::type
myFct(T arg1, Types ... rest) { /*do numeric stuff*/ }

template<typename T, typename ... Types>
typename std::enable_if<
    !std::is_arithmetic<T>::value
>::type
myFct(T arg1, Types ... rest) { /*do non-numeric stuff*/ }

This gets very unwieldy once you have more than just two mutually exclusive options, but this will definitely work.

like image 142
Barry Avatar answered Jan 20 '23 05:01

Barry