模板函数仅适用于VS



我已经用模板编写了一个代码,但它只能在Visual Studio中使用(不能在Dev c++或任何在线编译器中使用。我不明白为什么。

#include <iostream>
using namespace std; 
template <class Q1,class Q2,class Q3> // but when i write instead of 3 classes  1 class it will work 
//everywhere, how could it be possible?
void min(Q1 a, Q2 b, Q3 c) {
if (a <= b && a <= c) { 
cout << "nMinimum number is: " << a << endl; }
if (b < a && b < c) {
cout << "nMinimum number is: " << b << endl; }
if (c < a && c < b) { 
cout << "nMinimum number is: " << c << endl; }
}
int main()
{
double x,y,z;
cout << "Enter 3 numbers: " << endl;
cin >> x;
cin >> y;
cin >> z;
min(x, y, z);
}
函数std::min是隐式使用的。这是因为重载解析更喜欢非模板函数而不是模板函数,并且一些编译器工具集允许通过现有的#include访问std::min(C++标准在这件事上唯一要说的是,一旦达到#include <algorithm>std::min就必须可用(。

删除using namespace std;是一个解决方案,无论如何都是个好主意。教程经常使用它来澄清问题,但很少在生产代码中找到它。

最新更新