Jump to content
  • Advertisement
Sign in to follow this  
supagu

[c++] overriding template class

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

i've got a template wit the following function definition: template <class T> Packet& operator &(Packet& packet, T& data) this is a non-intrusive template function so i can add any class to a 'packet', but i want to be able to override this version with any custom version eg: template <class T> Packet& operator &(Packet& packet, std::string& data) but when i do this, the base template version gets called. Any ideas on how to do this? I think they do it in boost library somehow.

Share this post


Link to post
Share on other sites
Advertisement
Quote:


template <class T>
Packet& operator &(Packet& packet, T& data)

template <class T>
Packet& operator &(Packet& packet, std::string& data)



The latter is not a specialization of the former, as you still have an unbound template parameter T. You have to either do a correct specialization or use the regular function overloading:


// Either:
template <>
Packet& operator &<std::string>(Packet& packet, std::string& data);

// Or simply:
Packet& operator &(Packet& packet, std::string& data);


There are some gotchas you need to be vary of, though. Please read the following articles by Herb Sutter:

http://www.gotw.ca/gotw/049.htm
http://www.gotw.ca/publications/mill17.htm

Share this post


Link to post
Share on other sites
Quote:


// Either:
template <>
Packet& operator &<std::string>(Packet& packet, std::string& data);

// Or simply:
Packet& operator &(Packet& packet, std::string& data);



im not sure if this is mentioned in one of the two gotcha links you posted but the second one doesnt actualy do template specialization it defines a non-template overload of the operator. :-)

Share this post


Link to post
Share on other sites
Yes, as I said. The point is that it is semantically almost equivalent, and, as explained in the second link, usually the better alternative of the two.

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!