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

c – 折叠表达式模板参数推断替换失败,第1张

概述试图学习折叠表达式.参数推断的获取错误失败 #include<iostream>template <typename T>struct sum{ T value; template <typename ... Ts> sum(Ts&&...values) : value{(values + ...)}{}//error here};int main(){ 试图学习折叠表达式.参数推断的获取错误失败

#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,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,4);

DEMO

我该如何解决这个错误?

解决方法 这不是折叠表达式.编译器抱怨,因为它无法推断出类型名称T.

要解决这个问题,你可以在课程定义之后提供一个deduction guide,如下所示:

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

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

但我宁愿把总和作为一个功能.无论如何,让它成为一个班级有什么意义?

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

以上是内存溢出为你收集整理的c – 折叠表达式模板参数推断/替换失败全部内容,希望文章能够帮你解决c – 折叠表达式模板参数推断/替换失败所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1217854.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-05
下一篇2022-06-05

发表评论

登录后才能评论

评论列表(0条)

    保存