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

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

浏览一些模板教程时遇到以下错误:

Error (active) E0304 no instance of overloaded function "sum" matches the argument list Templates

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

#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:\Users\erind\source\repos\Templates\Templates\Templates.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...)) 递归设置 return 类型但不起作用。

从 C++14 开始,您可以简单地使用 auto,无需尾随 return 类型

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 + ...); }