我正在尝试了解 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;
}
编译时出现如下错误
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";
^
虽然取消注释正常功能和注释模板版本工作正常。为什么歧义不在正常功能中以及为什么在模板化版本中