C ++ pattern for numeric types

I want to have a template for selecting by numeric types, but also want to have a global type template. I tried to apply a solution for this question, but this did not 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 is the right way to do something like:

template<typename T, typename ... Types>
void myFct(T arg1, Types ... rest) 
{ 
    if (isNumeric(T))
        doNumericStuff();
    else
        doStuff();
}
+4
source share
2 answers

There are probably better ways to do this, but the easiest way is to simply click enable_ifon 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 becomes very cumbersome if you have no more than two mutually exclusive options, but it will definitely work.

+5
source

, " ", , .

template <typename T>
void do_stuff(T arg, std::true_type) {
  std::cout << "number\n";
}

template <typename T>
void do_stuff(T arg, std::false_type) {
  std::cout << "not-number\n";
}

void myFct() { }

template<typename T, typename... Ts>
void myFct(T arg1, Ts... rest) {
    // is_arithmetic will derive either true_type or false_type
    do_stuff(arg1, std::is_arithmetic<T>{});
    myFct(rest...); // recurse
}

, - "static if"

myFct(1, std::string{}, 2.0);,

number
not-number
number
+4

Source: https://habr.com/ru/post/1589260/


All Articles