generic functions(template functions)

T

Tony Johansson

Hello Experts!

Assume I have one function that is a template function called add and one
concrete function that also have the name add is it any point to make a
concrete function add in this example?

template <typename T>
T add(T rh, T lh)
{ return rh+lh; }

template <typename T>
int add(int rh, int lh)
{ return rh+lh; }
int main()
{
int i=1, j=2;
cout << "result " << add<int>(i,j) << endl;

return 0;
}

//Many thanks

//Tony
 
S

Srini

Hello Experts!
Assume I have one function that is a template function called add and one
concrete function that also have the name add is it any point to make a
concrete function add in this example?

template <typename T>
T add(T rh, T lh)
{ return rh+lh; }

template <typename T>
int add(int rh, int lh)
{ return rh+lh; }
int main()
{
int i=1, j=2;
cout << "result " << add<int>(i,j) << endl;
return 0;

}

In the above example there's no point for the template
specialization(That's the term you'd want to use). In general you'd
want to specialize a function template when you want to have different
behavior for particular types.

Srini
 
B

benben

Srini said:
In the above example there's no point for the template
specialization(That's the term you'd want to use). In general you'd
want to specialize a function template when you want to have different
behavior for particular types.

Srini

The code by Tony didn't look to me like template specialization. A full
specialization of function template add<> would look like:

template <>
int add(int rh, int lh)
{
return rh + lh;
}
 
S

Srini

The code by Tony didn't look to me like template specialization. A full
specialization of function template add<> would look like:

template <>
int add(int rh, int lh)
{
return rh + lh;
}

Yeah - even I thought so. But I checked compiling both forms (What OP
has given and what you've given) and both gave same results. I thought
that specialization was what the OP meant in his post.
 

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,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top