为什么即使我定义了它们"no matching overload found"也会出现错误

Why is "no matching overload found" error appearing even though I have them defined

本文关键字:found overload 错误 matching no 定义 为什么      更新时间:2023-10-16

通过一些模板教程,我遇到了以下错误:

错误(活动(E0304 没有重载函数"sum"的实例与参数列表匹配 模板

我知道我在这里处理可变参数模板,但我不明白为什么没有检测到多个参数的重载。还值得一提的是,我遵循的教程中的确切代码不会引发任何错误。

#include <iostream>
#include <string>
#include <memory>
#include <tuple>
#include <array>
#include <vector>
#include <complex>
using namespace std;

typedef complex<double> cd;


// specialization for when there is only one argument
template <typename T>
T sum(T t) { return t; }
// -> defines a return type as a result of sum values
template<typename T, typename ...U>
auto sum(T t, U ...u) -> decltype(t + sum(u...))
{
return t + sum(u...);
}

void variadic()
{ 
cout << sum(1, 2, 3, 4) << endl;
}
int main()
{
//consuming_templates();
//template_functions();
variadic();
getchar();
return 0;
}

错误:

Severity    Code    Description Project File    Line    Suppression State
Error   C2672    'sum': no matching overloaded function found   Templates
Severity    Code    Description Project File    Line    Suppression State
Error   C2893    Failed to specialize function template 'unknown-type sum(T,U...)'  Templates   
Severity    Code    Description Project File    Line    Suppression State
Error   C2780    'T sum(T)': expects 1 arguments - 4 provided   Templates   C:UserserindsourcereposTemplatesTemplatesTemplates.cpp   35  

这是一部std::common_type的作品。

我的意思是。。。尝试重写sum()可变参数版本,如下所示

template<typename T, typename ...U>
auto sum(T t, U ...u) -> typename std::common_type<T, U...>::type
{
return t + sum(u...);
}

代码中的问题是

template<typename T, typename ...U>
auto sum(T t, U ...u) -> decltype(t + sum(u...))
{
return t + sum(u...);
}

您尝试使用decltype(t + sum(u...))递归设置返回类型,但不起作用。

从 C++14 开始,您可以简单地使用auto,而不使用尾随返回类型

template<typename T, typename ...U>
auto sum(T t, U ...u)
{
return t + sum(u...);
}

从 C++17 开始,您可以使用模板折叠并完全避免递归

template <typename ... U>
auto sum (U ... u)
{ return (u + ...); }