template function or template class

I

Ivan Liu

Hi, I have a question as in the title.

I have two choices. One is the template function

template <class T>
Add(T a, T b){ return a+b; }


and the template class or functor

template <class T>
class Add
{
public:
T operator () (T a, T b){ return a+b; };
};

which one is better?
 
L

Lyell Haynes

Ivan said:
Hi, I have a question as in the title.

I have two choices. One is the template function

template <class T>
Add(T a, T b){ return a+b; }


and the template class or functor

template <class T>
class Add
{
public:
T operator () (T a, T b){ return a+b; };
};

which one is better?

The second example is what's called a functor, and you would have to
create an instance of the class before being able to call the
operator() on it. In this specific instance, and not knowing how you're
using the functionality presented, the first one would probably be a
better choice. However, if you needed to keep some sort of state with
the function, then you'd probably want the second. It really depends on
what you're using it for.

Lyell
 
R

Rolf Magnus

Ivan said:
Hi, I have a question as in the title.

I have two choices. One is the template function

template <class T>
Add(T a, T b){ return a+b; }


and the template class or functor

template <class T>
class Add
{
public:
T operator () (T a, T b){ return a+b; };
};

which one is better?

Define "better".
The advantage of the first one is that it's simpler. The advantage of the
second is that you can store some additional state in it and that it as in
some cases better optimization potential. You can also derive it from
std::binary_function to use it with certain algorithms that a function
doesn't work with.

Btw: Something like this already exists as std::add.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,218
Latest member
JolieDenha

Latest Threads

Top