How to implement the default operator << (ostream &, T) for a type without this operator?

Since it was std::to_stringadded in C ++ 11, I started to implement to_stringinstead of the more traditional one operator<<(ostream&, T). I need to link them together to include libraries that rely on operator<<(ostream&, T). I want to be able to express that if T has operator<<(ostream&, T), use it; otherwise use std::to_string. I am prototyping a more limited version that allows operator<<for all enumeration classes.

enum class MyEnum { A, B, C };

// plain version works
//std::ostream& operator<<(std::ostream& out, const MyEnum& t) {
//  return (out << to_string(t));
//}

// templated version not working
template<typename T, 
         typename std::enable_if<std::is_enum<T>::value>::type
>
std::ostream& operator<<(std::ostream& out, const T& t) {
  return (out << to_string(t));
}

Compiler says error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'MyEnum') cout << v << endl;

Questions:

  • Why is the template function not found by the compiler?
  • Is there a way to implement a common solution?
+4
source share
1 answer

, std::to_string, const MyEnum ( clang-703.0.31).

#include <iostream>
#include <type_traits>

enum class MyEnum { A, B, C };

template<typename T>
typename std::enable_if<std::is_enum<T>::value, std::ostream &>::type
operator<<(std::ostream& out, const T& t) {
    return (out << std::to_string(t));
}

int main() {
  MyEnum a;

  std::cout << a << std::endl;
}

docs std::enable_if, , valid, T - ( ). . std::is_enum<T>::value true, std::enable_if<std::is_enum<T>::value, std::ostream &>::type std::ostream & ( ) .

- my::to_string, :

namespace my {

    template<typename T>
    typename std::enable_if<! std::is_void<T>{} && std::is_fundamental<T>{}, std::string>::type
    to_string(T t) {
        return std::to_string(t);
    }

    std::string to_string(std::nullptr_t) = delete;

    std::string to_string(MyEnum a) {
        return "This is an enum";
    }
}

my::to_string std::to_string operator<<:

return (out << my::to_string(t));

EDIT: my::to_string , void std::nullptr_t.


docs:

// 2. the second template argument is only valid if T is an integral type:
template < class T,
       class = typename std::enable_if<std::is_integral<T>::value>::type>
bool is_even (T i) {return !bool(i%2);}

, class = /* enable_if stuff */, template< typename T, /* enable_if stuff */ >. , , - , std::to_string, enum .

+2

All Articles