I have a class tPoint that would be implemented having different base types so
template<typename T>class tPoint{
T x;
T y;
public:
void Set(T ix, T iy){x=ix;y=iy;}
};
When the type T is int, tPoint<int>
, I want a special Set(float, float) so I can round the values before assignation.
I thought that with specialisation I could:
template<> void tPoint<int>::Set(float ix,float iy){x=ix+.5; y=iy+.5;}
This way the compiler complains that there's no matching function in the class definition.
But if I declare in the class Set(float,float) then it says that's already defined (when it compiles for T =float)
I hope I made myself clear, what would be a clean approach to this or I'm doing something wrong? thanks!
You may overload a function template either by a non-template function or by another function template. The function call f(1, 2) could match the argument types of both the template function and the non-template function.
Function declarations that differ only by its return type cannot be overloaded with function overloading process. Member function declarations with the same parameters or the same name types cannot be overloaded if any one of them is declared as a static member function.
Function overloading is used when multiple functions do similar operations; templates are used when multiple functions do identical operations. Templates provide an advantage when you want to perform the same action on types that can be different.
The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.
You need to specialize the class, like this:
template<> class tPoint<int>{
int x;
int y;
public:
void Set(int ix, int iy){x=ix;y=iy;}
void Set(float ix, float iy){x = ix+0.5; y = iy+0.5;}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With