ApprenticeHacker
ApprenticeHacker

Reputation: 22031

When should I use templates and when overloaded functions?

I am confused. I never seem to decide what to use, a template or an overloaded function. Overloads need more coding. So in what cases is it preferred to use templates and in what overloaded functions?

For example, i recently had to take this decision while making a small GBA game. There were two types u16 and int and i decided to use overloaded functions.

inline void Point::Move(int x, int y) {_ix += x; _iy += y; }
inline void Point::Move(u16 x, u16 y) {_ix += (int) x; _iy += (int) y; }

should I have used a template instead? And in what cases should I use an overloaded function?

Upvotes: 1

Views: 378

Answers (3)

Yochai Timmer
Yochai Timmer

Reputation: 49271

Usually you would overload a function when you know the types that you are going to use.

Usually you will overload a function when there's an actual logical difference (different code) between the types you're using.
And you can do that because you know the actual types and their traits.

The power of templates is that you can write the function it once, and then use the method for any type you want.
But the template should be general enough to fit any type given to it.

Upvotes: 1

Alok Save
Alok Save

Reputation: 206636

Basic Rule should be:

Use Templates when you want to perform same functionality/Operations on different data types.

Use overloaded functions when you want to perform different functionality/Operations on different/same data types

Also, A good measure of when you really need a overloaded function over template is when you are making too many explicit specializations for a templated version of function.

In your example if you performing same operations in both the versions of the functions, You should use templates, else you should use Overloaded function.

Upvotes: 8

David Heffernan
David Heffernan

Reputation: 613501

As far as I can see a template solution would result in the same compiled object but no repetition in the source. A clear win for templates.

I don't understand the point about templates needing more memory. That sounds like a misthink.

Upvotes: 3

Related Questions