View Full Version : templates
mickey
15th January 2008, 21:10
Hello, I have some question:
template<class T>
void swap(T* a, T* b) {
T temp = *a;
*a = *b;
*b = temp;
}
int x,y;
swap(&x,&y);
swap(x,y); //why this compile and it works?
template<class T>
void swap(T* a, T* b) {
T* temp = *a;
*a = *b;
*b = temp; // *b = *temp; /*with this same problem before */
}
int x,y;
swap(&x, &y); //why now this doens't compile?
swap(x, y); // why this compile
For what I knew, with void swap(T* a, T* b), should only work swap(&x, &y);
Thanks in advance.
marcel
15th January 2008, 21:39
Compiling with msvc, right?
You don't get any error because the compiler uses this function instead, defined in include/utility.
template<class _Ty> inline
void swap(_Ty& _Left, _Ty& _Right)
{ // exchange values stored at _Left and _Right
if (&_Left != &_Right)
{ // different, worth swapping
_Ty _Tmp = _Left;
_Left = _Right;
_Right = _Tmp;
}
}
Rename your function and you'll see the errors.
jacek
15th January 2008, 21:54
Do you have "using namespace std" anywhere in your source code?
mickey
15th January 2008, 22:59
Do you have "using namespace std" anywhere in your source code?
yes, I have only main.cpp and I have using namespace std;
But with Marcel hint, I solve every problem....but for me this is strange! Something more about avoid this problem? (apart change name to functions)
It gets me the same error with:
template<class T>
T min(const T& a, const T& b ) {
if( a < b )
return( a ) ;
else
return( b ) ;
}
but change to 'mymin' everything seems to work....
marcel
15th January 2008, 23:17
Yes, these functions are already defined in utility.h, which gets included before your header.
Try defining your functions in a separate namespace and access them with the scope resolution operator(myNameSpace::min or myNameSpace::swap).
jacek
16th January 2008, 15:25
yes, I have only main.cpp and I have using namespace std;
You wouldn't have such problems without that line. It's better to use std:: prefix for all functions and classes from standard namespace.
Powered by vBulletin® Version 4.2.5 Copyright © 2024 vBulletin Solutions Inc. All rights reserved.