Jump to content
  • Advertisement
Sign in to follow this  
The C modest god

Template method?

This topic is 4877 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

If I have only one method of the class with a template parameter. Do I need to write template<class T> before the class? If so, do I need to write all its methods implementations in an .h file eventhough they have no template parameters? Thanks in advance.

Share this post


Link to post
Share on other sites
Advertisement
Sorry Misunderstood the question.

[Edited by - HAM on July 14, 2005 9:07:28 AM]

Share this post


Link to post
Share on other sites
No, you don't need to template the whole class if you only want one member function to be templated.


#include <iostream>

class SomeClass {
public:
template <typename T>
void template_function(const T & t) {
std::cout << t << std::endl;
}
};


int main(int, char **) {
SomeClass s;
s.template_function(5);
s.template_function("cow");

return 0;
}

Only the template members need to go into the header. If you have non-template member functions they can go into a source file like normal.

Share this post


Link to post
Share on other sites
And if the compiler can't work which version of the templated function to use from the parameters you provide (if it doesn't take a parameter of type T) you call it like this:


obj.Function<int>();
obj.Function<std::string>();

Share this post


Link to post
Share on other sites
Quote:
Original post by The C modest god
If I have only one method of the class with a template parameter. Do I need to write template<class T> before the class?
If so, do I need to write all its methods implementations in an .h file eventhough they have no template parameters?

Thanks in advance.


No. You only have to write <template class T> before the function. And only the templated function needs to be in the .h file.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!