C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了c – 折叠表达式模板参数推断/替换失败大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
试图学习折叠表达式.参数推断的获取错误失败

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

错误

@H_384_7@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 – 折叠表达式模板参数推断/替换失败所遇到的程序开发问题。

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

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。