折叠表达式模板参数推断/替换失败

Har*_*ngh 3 c++ c++17

试图学习折叠表达式.参数推断的获取错误失败

#include<iostream>

template <typename T>
struct sum{
    T value;
    template <typename ... Ts>
    sum(Ts&&...values) : value{(values + ...)}{}//error here
};
int main()
{
    sum s(2,3,4);
}
Run Code Online (Sandbox Code Playgroud)

错误

main.cpp: In function 'int main()':
main.cpp:11:16: error: class template argument deduction failed:
     sum s(2,3,4);
                ^
main.cpp:11:16: error: no matching function for call to 'sum(int, int, int)'
main.cpp:7:5: note: candidate: template<class T, class ... Ts> sum(Ts&& ...)-> sum<T>
     sum(Ts&&...values) : value{(values + ...)}{}
     ^~~
main.cpp:7:5: note:   template argument deduction/substitution failed:
main.cpp:11:16: note:   couldn't deduce template parameter 'T'
     sum s(2,3,4);
Run Code Online (Sandbox Code Playgroud)

DEMO

我该如何解决这个错误?

Hol*_*Cat 7

这不是折叠表达式.编译器抱怨,因为它没有办法推断出typename T.

要解决这个问题,您可以在课程定义后提供演绎指南,如下所示:

template <typename ...P> sum(P &&... p) -> sum<decltype((p + ...))>;
Run Code Online (Sandbox Code Playgroud)

或者,您可以手动指定参数: sum<int> s(2,3,4);


我宁愿做sum一个功能.无论如何,让它成为一个班级有什么意义?

template <typename ...P> auto sum (P &&... p)
{
    return (p + ...);
}
Run Code Online (Sandbox Code Playgroud)