小编she*_*rey的帖子

在C++中,变量模板有没有办法忽略非算术类型或对象并返回剩余参数的总和?

我想实现一个如问题标题所述的功能,例如:

cout << SumValue("abc", string("abcd"), 1.3, 1, 10, 2, 100) << endl;  
Run Code Online (Sandbox Code Playgroud)

我想要 C++ 代码片段输出、和忽略和114.3的总和。 我尝试了变量模板函数并使用库作为代码如下:1.3, 1, 10, 2 and 100"abc"string("abcd")
<type_traits>

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...);
}
Run Code Online (Sandbox Code Playgroud)

但编译器报错:

error: invalid operands of types 'const char*' and 'long double' to binary 'operator+'
     return …
Run Code Online (Sandbox Code Playgroud)

c++ templates c++11

5
推荐指数
1
解决办法
93
查看次数

标签 统计

c++ ×1

c++11 ×1

templates ×1