Archived

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

Templates

This topic is 5131 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Is it possible to template a funtion without templating a class? I have a function that has the exact same procedures with any return type. Any way I can do that?
template<class T> T Row(int m_Col);

Share this post


Link to post
Share on other sites
Yes. However, automatically parameterizing purely by the return type is not possible, for the same reasons that functions cannot be overloaded purely by their return types.


"Sneftel is correct, if rather vulgar." --Flarelocke

Share this post


Link to post
Share on other sites

int fn(int);
float fn(int);

That is not an acceptable pair of overloaded functions because the compiler has no way of knowing which one you called in the event that you do something like this:

fn(3);

For the same reason, the example you posted is not an an acceptable parametrized function.

Share this post


Link to post
Share on other sites
This works:


template< int N > int shift( int m ) { return m >> N; }


You call it like so:


int x = shift<16>( y );


Similarly, this works:


template< class N > N cast( int m ) { return (N)m; }


You call it like so:


int i = 3;
float f = cast<float>( i );


You can even take the address of these functions. However, the compiler can't derive the instantiation if you do NOT specify the specialization you want. This wouldn't work:


int i = 3;
float f = cast( i );


That's because C++ is not perl, so the type of the calling context does not matter in C++.


Edit: stupid template/html tags.

[edited by - hplus0603 on November 26, 2003 6:57:37 PM]

Share this post


Link to post
Share on other sites