vendredi 22 mai 2015

How to limit a templated function if a specialization exist?

I'm writing a library for which each value type can be converted to string using a to_string() free function.

I'd like to enable std::ostream& operator<<(std::ostream&, _) for all types T for which to_string(T) is valid. Here is my try:

namespace mylibrary {

// All my types are declared in the `mylibrary` namespace so that ADL is happy.

template <typename T>
inline std::string to_string(const T& value) {
    // Return a string for value. Doesn't really matter how.
}

template <typename T>
inline std::ostream& operator<<(std::ostream& os, const T& value) {
    return os << to_string(value);
}

}

This actually works... but a bit too well: when resolving os << to_string(value) my templated operator<<() is picked up as candidate even for std::string which sadly makes the call ambiguous an ends up in a compiler error.

I tried using std::enable_if<> to conditionnaly disable my operator<< but sadly I couldn't get something that compiles.

How can I restrict my operator<<() for types for which to_string(T) is a valid expression ?

Alternatively, is there way to restrict my operator<<() for types which are defined in my namespace ?

Aucun commentaire:

Enregistrer un commentaire