Reputation: 218
To write an object into the command line (or other output streams) it is possible to overload the <<
operator. But is there any possibility to achieve this for templates?
Assume I have the following:
template <typename identifier>
class SomeTemplate {
public:
SomeTemplate();
~SomeTemplate();
void addElement(identifier id, unsigned int elem);
unsigend int getElement(identifier id);
private:
std::map<identifier, unsigned int> data_map_;
};
When I now specialize the class with e.g. an identifier of type std::tuple<unsigned int, unsigned int, unsigned int>
The Function getElement(identifier id)
should perform a consistency check and write a warning to std::cout
in case the requested element is not present in data_map_
.
Simply passing id to cout does not work, since there is possibly no overloaded <<
operator for the type used for specialization.
Is there any other possibility to achieve this? Maybe its possible that identifier has to implement an pure virtual class which forces all identifiers to overload the <<
operator. But is this possible?
Thanks for your help.
Regards
Upvotes: 1
Views: 236
Reputation: 4207
Your first question "is there any possibility to [overload operator<<] for templates"? Of course...
template <typename identifier>
std::ostream& operator<<(std::ostream& out, SomeTemplate<identifier> const& rhs);
A definition for that declaration would work just fine.
However, what you are really asking is, can I stream std::tuple
? The answer appears to be no. You could, of course, write a local operator<<
for it, but don't expose it too widely.
Upvotes: 1
Reputation: 249582
The usual thing to do would be to simply state that having a stream output operator is a prerequisite for the identifier
type. This is surely more in the spirit of generic C++ programming using templates than would be a base class with pure virtual method to print.
If you must, perhaps you can use SFINAE to print a simple "unavailable" message if there's no stream output operator for a particular type.
Upvotes: 3