Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overloaded member functions for a particular template specialisation

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!

like image 653
tru7 Avatar asked Feb 26 '11 17:02

tru7


People also ask

Can a template function be overloaded?

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.

Can member functions be overloaded?

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.

How are overloaded functions and function templates alike How are they different?

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.

What is function template specialization?

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.


1 Answers

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;}
};
like image 140
Karl Bielefeldt Avatar answered Sep 20 '22 04:09

Karl Bielefeldt