Home > database >  In C , is there any way for variatic template to ignore non-arithmetic type or object and return th
In C , is there any way for variatic template to ignore non-arithmetic type or object and return th

Time:03-02

I want to realize a function as the question title described, for example:

cout << SumValue("abc", string("abcd"), 1.3, 1, 10, 2, 100) << endl;  

I want that C snippet output 114.3, the sum of 1.3, 1, 10, 2 and 100, and ignore "abc" and string("abcd").
I have tried the variatic template function and used the <type_traits> lib as codes below:

template <typename T>
long double SumValue(T first)
{
  if (is_arithmetic<T>::value)
    return first;
  else
    return 0;
}

template <typename T, typename... Args>
long double SumValue(T first, Args... args)
{
  if (is_arithmetic<T>::value)
    return first   SumValue(args...);
  else
    return SumValue(args...);
}

But compiler reports an error:

error: invalid operands of types 'const char*' and 'long double' to binary 'operator '
     return first   SumValue(args...);
            ~~~~~~^~~~~~~~~~~~~~~~~~~

I can understand the error described, but, I cannot figure out a solution for it.

CodePudding user response:

You can overload SumValue with the help of SFINAE.

template <typename T>
typename std::enable_if<std::is_arithmetic<T>::value, long double>::type
SumValue(T first)
{
  return first;
}
template <typename T>
typename std::enable_if<!std::is_arithmetic<T>::value, long double>::type
SumValue(T first)
{
  return 0;
}

template <typename T, typename... Args>
long double SumValue(T first, Args... args)
{
  return SumValue(first)   SumValue(args...);
}

LIVE

BTW: Since C 17 you can use Constexpr If.

template <typename T>
long double SumValue(T first)
{
  if constexpr (std::is_arithmetic<T>::value)
    return first;
  else
    return 0;
}

template <typename T, typename... Args>
long double SumValue(T first, Args... args)
{
  return SumValue(first)   SumValue(args...);
}

LIVE

  • Related