1

I have written a code with template but it works only with Visual Studio( not in Dev c++ or any online compiler. I don't understand why.

#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);
}
  • 4
    `using namespace std;` - remove this and type `std::` where needed. `std::min` is a thing, you don't want name conflicts. – Mat Nov 13 '19 at 16:59
  • 1
    Please copy/paste the error into your question. – Quentin Nov 13 '19 at 17:00
  • error: ‘__comp’ cannot be used as a function –  Nov 13 '19 at 17:01
  • 3
    The compiler cannot distinguish between your function and [`std::min`](https://en.cppreference.com/w/cpp/algorithm/min). It just happens that MSVC didn't `#include ` within `iostream`, but other compilers did (and they are perfectly allowed to do so). – Yksisarvinen Nov 13 '19 at 17:01
  • Yep, or change it to `::min(x, y, z)`. Your own function is conflicting with `std::min` and this is a good example why `using namespace` is bad. – Lukas-T Nov 13 '19 at 17:02
  • @churill soyou mean if I remove _using namespace_ it will work? –  Nov 13 '19 at 17:05
  • Oh , I understood,Thanks to everyone)) –  Nov 13 '19 at 17:15

1 Answers1

3

The function std::min is used implicitly. That's because overload resolution favours non-template functions over template ones, and some compiler toolsets allow std::min to be reachable via the #includes you have (the only thing the C++ standard has to say on the matter is that std::min must be available once #include <algorithm> is reached).

Dropping using namespace std; is one fix, and is a good idea anyway. Tutorials often use it for clarity, but it's rare to find it in production code.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483