What's wrong with this code....


//templates
#include<iostream>
using namespace std;

template <class t>
t max (t w,t x) --->here i get no error if I use &w and &x in place of w and x...{

if(w>x)
return w;
else
if(w!=x)
return x;
}

int main()
{
int a=10,b=343,c;
c=max(a,b);

cout<<"Max="<<c;
float d=2.99,e=3.4,f;
f=max(d,e);

cout<<"\nMax="<<f;

system("pause");
return 0;
}
compiler gives an error:: call of overloaded `max(int&, int&)' is ambiguous

You have a name collision with the standard library.

#include<iostream>

template <typename T> inline const T& max (const T & w,const T & x) { return w > x ? w : x; }

int main()
{
	int a = 10, b = 343;
	std::cout << max(a, b) << std::endl;
	std::cout << std::max(a, b) << std::endl;
	return 0;
}

You can do one of two things to avoid the name clash:
1) Remove the using namespace std; 2) Use ::max to indicate the locally scoped version of the function

This is one of the caveats of that using namespace std approach.

Another approach is to create your own namespace :

#include <iostream>
using namespace std;

namespace Util{
 template<typename T>
 T& max(const T& lhs, const T& rhs){ return lhs < rhs ? rhs : lhs ; }
};
int main(){
 cout << Util::max(1,2) << endl;
}
commented: Like your simple solution +5

I just really like this "better" C++ code then #define MAX(a,b) (a>b)?a:b. Yes, I know that in this usage MAX(i++,j++) is wrong (to be honest I'd just use using namespace std and max function).

I just really like this "better" C++ code then #define MAX(a,b) (a>b)?a:b. Yes, I know that in this usage MAX(i++,j++) is wrong (to be honest I'd just use using namespace std and max function).

Regardless of the ultimate version implemented, it is a responsibility for us as developers to understand the ramifications of our decisions. Otherwise we all waste our time chasing these silly mistakes.

yeah! got it I didn't consider max as a predefined function/// thanks for your comments

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.