【问题标题】:Template function only works with VS [duplicate]模板功能仅适用于 VS [重复]
【发布时间】:2020-03-09 12:57:24
【问题描述】:

我用模板编写了一个代码,但它只适用于 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);
}

【问题讨论】:

  • using namespace std; - 删除它并在需要的地方输入std::std::min 是一个东西,你不想名字冲突。
  • 请将错误复制/粘贴到您的问题中。
  • 错误:“__comp”不能用作函数
  • 编译器无法区分你的函数和std::min。碰巧 MSVC 没有在 iostream 中使用 #include &lt;algorithm&gt;,但其他编译器做到了(并且完全允许他们这样做)。
  • 是的,或者将其更改为::min(x, y, z)。您自己的函数与std::min 冲突,这是为什么using namespace 不好的一个很好的例子。

标签: c++ visual-studio dev-c++


【解决方案1】:

函数std::min 被隐式使用。那是因为重载决议有利于非模板函数而不是模板函数,并且一些编译器工具集允许通过您拥有的#includes 访问std::min(C++ 标准对此唯一要说的是std::min必须在到达 #include &lt;algorithm&gt; 后可用)。

删除using namespace std; 是一种解决方法,无论如何都是个好主意。教程经常为了清晰起见使用它,但很少在生产代码中找到它。

【讨论】:

    猜你喜欢
    • 2019-07-30
    • 2021-08-26
    • 2022-01-16
    • 2015-10-28
    • 2019-01-01
    • 2011-12-16
    • 2017-12-22
    • 1970-01-01
    相关资源
    最近更新 更多