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

Fold Expression template argument deduction/substitution failed

本文关键字:替换 失败 参数 表达式 折叠      更新时间:2023-10-16

尝试学习折叠表达式 .参数推断错误失败

#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);
}

错误

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);

演示

如何修复此错误?

这与折叠表达式无关。编译器抱怨,因为它无法推断typename T

为了解决这个问题,你可以在类定义之后提供一个演绎指南,如下所示:

template <typename ...P> sum(P &&... p) -> sum<decltype((p + ...))>;

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


但我宁愿sum函数。无论如何,把它变成一个类有什么意义?

template <typename ...P> auto sum (P &&... p)
{
return (p + ...);
}