模板化的ostream重载歧义错误:basic_ostream <char> vs const char []

Abh*_*xit 4 c++ templates

我试图了解ostream重载.考虑一下

#include <iostream>

using std::ostream;

enum class A{a1, a2, a3};

template <class T>
ostream& operator<<(ostream& out, const T& a)
{
  switch(a)
    {
    case T::a1 :
      return out<<"a1";
    case T::a2 :
      return out<<"a2";
    case T::a3 :
      return out<<"a3";
    };
  return out;
}
/*ostream& operator<<(ostream& out, const A& a)                               
{                                                                              
  switch(a)                                                                    
    {                                                                          
    case A::a1 :                                                               
      return out<<"a1";                                                        
    case A::a2 :                                                               
      return out<<"a2";                                                        
    case A::a3 :                                                               
      return out<<"a3";                                                        
    };                                                                         
  return out;                                                                  
  }*/

int main()
{
  A a = A::a3;
  std::cout<<a<<std::endl;
}
Run Code Online (Sandbox Code Playgroud)

编译时我得到如下错误

test.cpp:13:17: error: ambiguous overload for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream<char>}’ and ‘const char [3]’)
       return out<<"a1";
                 ^
Run Code Online (Sandbox Code Playgroud)

虽然取消注释正常功能和评论模板版本工作正常.为什么歧义不在正常功能中以及为什么它在模板化版本中

And*_*owl 5

非模板运算符不会导致任何歧义,因为该运算符本身不适用于解析此调用:

return out << "a1";
//     ^^^^^^^^^^^
//     This MUST be `std::operator <<`, no other valid overload of
//     operator << is found!
Run Code Online (Sandbox Code Playgroud)

以及其他类似的.

另一方面,模板版本是可行的,因为T它不一定是任何具体类型:

template <class T>
ostream& operator<<(ostream& out, const T& a)
{
    switch(a)
    {
    case T::a1 :
      return out << "a1";
//           ^^^^^^^^^^^
//           Here the compiler could invoke std::operator <<
//           OR it could invoke your operator << template,
//           which is also viable since T could be anything!
//           Which one should it pick?

    // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,编译器不知道是否在std命名空间或函数模板中选择重载(是的,这将尝试建立无限递归,但编译器不需要关心).

那些重载都很好,因此含糊不清.

解决问题的一种方法是SFINAE约束您的模板重载,operator <<以便仅在T枚举类型时才考虑重载解析.例如:

#include <type_traits>

template <class T, 
    typename std::enable_if<std::is_enum<T>::value>::type* = nullptr>
ostream& operator<<(ostream& out, const T& a)
Run Code Online (Sandbox Code Playgroud)

这是一个实例.