[英]C++ Template function not working in Visual Studio 2019 [Error 2668]
在通用交换 function 中使用模板函数时出错:
#include <iostream>
#include <complex>
using namespace std;
template <class T>
inline void swap(T& d, T& s)
{
T temp = d;
d = s;
s = temp;
}
int main()
{
int m = 5, n = 10;
double x = 5.3, y = 10.6;
complex<double> r(2.4, 3.5), s(3.4, 6.7);
cout << "inputs: " << m << "," << n << endl;
swap(m, n);
cout << "outputs: " << m << "," << n << endl;
cout << "double inputs: " << x << "," << y << endl;
swap(x, y);
cout << "double outputs: " << x << "," << y << endl;
cout << "complex inputs: " << r << "," << s << endl;
swap(r, s);
cout << "complex outputs: " << r << "," << s << endl;
return 0;
}
有人可以在这里发现错误吗? 我在三个调用函数处收到错误:
错误 C2668 'swap':对重载 function 的模糊调用
我改成std::格式,即代码:
#include <iostream>
#include <complex>
template <class T>
inline void swap(T& d, T& s)
{
T temp = d;
d = s;
s = temp;
}
int main()
{
int m = 5, n = 10;
double x = 5.3, y = 10.6;
std::complex<double> r(2.4, 3.5), s(3.4, 6.7);
std::cout << "inputs: " << m << "," << n << std::endl;
swap(m, n);
std::cout << "outputs: " << m << "," << n << std::endl;
std::cout << "double inputs: " << x << "," << y << std::endl;
swap(x, y);
std::cout << "double outputs: " << x << "," << y << std::endl;
std::cout << "complex inputs: " << r << "," << s << std::endl;
swap(r, s);
std::cout << "complex outputs: " << r << "," << s << std::endl;
return 0;
}
现在我得到了完整的错误:
SwapFunction.cpp(55,14): error C2668: 'swap': ambiguous call to overloaded function
SwapFunction.cpp(32,13): message : could be 'void swap<std::complex<double>>(T &,T &)'
with
[
T=std::complex<double>
]
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.28.29333\include\utility(102,19): message : or 'void std::swap<std::complex<double>,0>(_Ty &,_Ty &) noexcept(<expr>)' [found using argument-dependent lookup]
with
[
_Ty=std::complex<double>
]
所以我只在std::complex<double>
调用 function 中遇到错误,接下来可以做什么?
using namespace std
可能是这里的罪魁祸首,因为它将std::swap
拉入全局命名空间。
因此,您可以删除它并完全限定相关标识符(推荐)或重命名您自己的swap
function。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.