为什么即使我定义了它们"no matching overload found"也会出现错误
Why is "no matching overload found" error appearing even though I have them defined
通过一些模板教程,我遇到了以下错误:
错误(活动(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 + ...); }
相关文章:
- OpenCV Android C++ imwrite not found
- 解决"ld: library not found for -ltensorflow_framework.2.3.0"
- 加载与引用 .NET DLL 位于同一文件夹中的引用的 .NET DLL 时"Not found"异常
- 处理"no operator found"
- C++初学者:为什么我的编译器根据我的循环返回"name not found"?
- _BitScanForward64 can not be found
- 使用提升 asio 时出现"resolve: Host not found (authoritative)"异常
- 在C++中,是否可以"overload"作为另一个类成员的对象?
- 为什么 VScode 在 .h 文件中显示"'iostream' file not found"?
- 使用自定义 nodejs 插件时的"The specified module could not be found"
- Boost.Python 和导入 dll,"The specified module could not be found"
- 为什么我在" 'X' identifier not found' "上收到错误
- WinDBG适用于从Visual Studio 2015保存的转储,但不适用于任务管理器。显示异常代码"not found"
- "Entry Point Not Found" Azure 中的错误 LightGBM R 包
- TBB_tbb_LIBRARY_DEBUG-NOT FOUND
- 当索引为 1 时,_BitScanReverse返回 0,这意味着根据 MS "no set bits were found"
- 为什么即使我定义了它们"no matching overload found"也会出现错误
- Android Studio 3.1.2 - 无法运行C++子例程"No implementation found for Java.lang.String..."
- 卢阿宾德: "No matching overload found, candidates:"
- 从 Luabind 调用C++成员函数会导致"No matching overload found"