小编Adi*_*arg的帖子

为什么我需要默认求和函数来实现可变参数模板求和?

我想计算提供给 function 的任意数量的参数的总和sum。假设给予函数的整数将满足operator+.

如果我注释掉该函数sum()(没有参数的函数),则代码无法编译。如果我取消注释,代码会编译并运行,但永远不会命中 function sum()

我似乎无法理解为什么我们需要有sum()功能,因为我正在使用条件sizeof...(Args)

如果有人能帮助我理解这一点,我会非常感激吗?

/*
int sum() 
{
    std::cout << "Sum with 0 Args" << std::endl;
    return 0;
}
*/

template <typename T, typename...Args>
T sum(T first, Args...args) 
{
    // std::cout << sizeof...(Args) << std::endl;
    if (sizeof...(Args) != 0) 
    {
        return first + sum(args...);
    }
    else 
    {
        std::cout << "Found 0 args" << std::endl;
        return first;
    }
}

int main()
{
    std::cout << sum(1, 2, 3) …
Run Code Online (Sandbox Code Playgroud)

c++ templates function-templates variadic-templates c++14

0
推荐指数
1
解决办法
115
查看次数