template error

I am trying to write this simple code to test template functionality, but I get the following error:
Error 1 error C2668: 'min' : ambiguous call to overloaded function

Could you please tell me what's wrong?Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<iostream>
using namespace std;

template<class T>
T min(T a, T b);

template<class T>
T min(T a,T b)
{
	if(a<b)
		return a;
	return b;
}


void main()
{
	char c1='w', c2='x';
	int n1=10, n2=16;

	cout<<"min(w,x)="<<min(c1,c2)<<endl;
	cout<<"min(10,16)="<<min(n1,n2)<<endl;
}
The STL library writers got there before you.
There is already a template function call min in the std namespace.
Choose another name for your function (or keep the name and create your own namespace for it).
void main()

BADBADBADBADBAD! Use int main().

Anyway, your problem is that the function "min" is already declared on some systems. Just rename it "Min" or something.
thanks
Just to add to guestgulkan's response, #include <algorithm> will give you access to std::min() (which you are getting indirectly through iostream).
I'd buy the C++ Committee a round of beers if they took out using.
closed account (z05DSL3A)
I'd buy the C++ Committee a round of beers if they took out using.

using declarations or using directives, or both?

For those that don't know the difference:
using Declarations, ie:
1
2
3
using std::cout;
using std::cin;
using std::endl

add names to the scope in which they are declared. The effect of this is:
» a compilation error occurs if the same name is declared elsewhere in the same scope;
» if the same name is declared in an enclosing scope, the the name in the namespace hides it.

The using directive, ie using namespace std;, does not add a name to the current scope, it only makes the names accesable from it. This means that:
» If a name is declared within a local scope it hides the name from the namespace;
» a name in a namespace hides the same name from an enclosing scope;
» a compilation error occurs if the same name is made visible from multiple namespaces or a name is made visible that hides a name in the global name space.
Both. using defeats the purpose of organizing types and functions into namespaces. What's the point if the user can just override it if he feels like it?
Last edited on
closed account (z05DSL3A)
I must admit, I do hate seeing using directives, especially at global scope. It does negate the namespace concept and pulling everything from the namespace into the current scope is a bad idea.

I have less of a problem with using declarations, especially if their scope is kept restricted. Pulling names out of a namespace into the current scope can be beneficial.

Full scope resolution is desirable for production code.

As with a lot of things, if they are used to generally or without forethought, they can course problems.
Topic archived. No new replies allowed.