954,480 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

doubt in templates

What's wrong with this code....


//templates
#include
using namespace std;

template
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="<

agarg12
Newbie Poster
2 posts since Mar 2011
Reputation Points: 10
Solved Threads: 0
 

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;
}
gerard4143
Nearly a Posting Maven
2,272 posts since Jan 2008
Reputation Points: 512
Solved Threads: 387
 

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.

L7Sqr
Practically a Master Poster
656 posts since Feb 2011
Reputation Points: 201
Solved Threads: 123
 

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;
}
firstPerson
Senior Poster
3,923 posts since Dec 2008
Reputation Points: 841
Solved Threads: 608
 

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).

Zjarek
Junior Poster in Training
79 posts since Oct 2009
Reputation Points: 20
Solved Threads: 18
 
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.

L7Sqr
Practically a Master Poster
656 posts since Feb 2011
Reputation Points: 201
Solved Threads: 123
 

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

agarg12
Newbie Poster
2 posts since Mar 2011
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: