dimanche 22 décembre 2019

Overloading operator<< for enum class inside template class

I can't seem to be able to overload operator<< for an enum class inside a template class:

#include <iostream>

template <typename T>
struct S
{
    enum class E { A, B };

    E e;
};

template <typename T>
std::ostream& operator<<(std::ostream& s, const typename S<T>::E e)
{
    return s << static_cast<int>(e);
}

int main()
{
    const S<int> s {};
    std::cerr << s.e;    // error
}

The exact error message produced by Visual Studio 2015 is:

error C2679: binary '<<': no operator found which takes a right-hand operand of type 'const S<int>::E' (or there is no acceptable conversion)

Both gcc and clang fail with a similar error message.

Two notes:

  • If I change the enum class to a plain enum, the code compiles fine.
  • If I specialize the operator<< overload for T = int, the code compiles fine as well.

What am I missing?

Aucun commentaire:

Enregistrer un commentaire