c++ - 模板化 Sum(Args...) 可变参数函数无法编译

标签 c++ templates variadic-templates

我使用静态结构成员技巧来强制执行第二遍编译,但仍然出现错误:

struct S
{
    template <typename T>
    static T Sum(T t) {
        return t;
    }

    template <typename T, typename ... Rest>
    static auto Sum(T t, Rest... rest) -> decltype(t + Sum(rest...) )
    {
        return t + Sum(rest...);
    }
};

int main()
{
    auto x = S::Sum(1,2,3,4,5);
}

main.cpp:17:14: 没有匹配函数来调用“Sum”

最佳答案

即使使用 clang 4.0 编译也会失败。

我设法使用 decltype(auto)(只有 auto 也可以)而不是显式尾部返回类型来编译它。

struct S
{
    template <typename T>
    static T Sum(T t) {
        return t;
    }

    template <typename T, typename ... Rest>
    static decltype(auto) Sum(T t, Rest... rest) 
    {
        return t + Sum(rest...);
    }
};

我认为编译器无法推导类型,因为推导仅取决于递归返回语句。

More info here

关于c++ - 模板化 Sum(Args...) 可变参数函数无法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45503734/

相关文章:

c++ - 为模板类声明模板方法

c++ - 如何使用参数包参数 typedef 函数指针类型

c++ - 非中止断言 CppUnit

c++ - 如何处理析构函数中销毁互斥体失败的情况

c++ - 精神X3 : Basic example for compound components does not compile

c++ - 编写自定义分配器

c++ - 在编译时自动生成用于稀疏数组索引的 switch 语句

C++ 可变参数模板方法特化

c++ - 这个语法是什么意思, `class template <class R, class ...Args> class name<R(Args...)>`

c++11 成员函数从 unique_ptr 的 vector 返回原始指针的 vector