[c++] overriding template class

Started by
3 comments, last by Sharlin 17 years, 6 months ago
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.
Advertisement
template <>Packet& operator &<std::string>(Packet& packet, std::string& data)


MSDN
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
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. :-)
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.

This topic is closed to new replies.

Advertisement