This topic is now archived and is closed to further replies.


template functions.

Recommended Posts

hi all, I was reading up with C++ book and it didnt make it quite clear about the template functions. For example, suppose you have this:
template <typename t>
void foo(t x);//function prototype.

and in the main code, you had this:
   int x = 10;
   double y = 10.0;
Obviously this would work. However, when you have foo(int x) set up as well, foo(int x) would override the template function. Is this correct? So, the book gives an example of overriding the template function:
template <typename t>
void foo(t x);//function prototype.

void foo(int x); // method1

void foo<int>(int x); //method2

template<> foo<int>(int x); //method3

template<> foo(int x); //method 4

The book tells me that all of these methods (1-4) are the same, ie, they would override the template. So, whats the point of using method2-4 other than making it harder to remember the syntax? Is the book mising the point or am I going crazy?? thanks... -Xtreme. [edited by - Xtreme on October 8, 2003 3:08:47 AM]

Share this post

Link to post
Share on other sites
It depends on what you're trying to do. The different syntaxes mean different things.

1 is classical C++ function overloading. They are useful when a function may take different argument types in its different incarnations, but have the same basic functionality.

2, 3 and 4 are template specialization. They indicate that you're defining a "special case" of the template, which should override the "generic" implementation already specified. Useful when certain datatypes you might use as template arguments need special treatment.

How appropriate. You fight like a cow.

[edited by - sneftel on October 8, 2003 3:12:43 AM]

Share this post

Link to post
Share on other sites