Sign in to follow this  
supagu

[c++] overriding template class

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
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this