在下面的简化示例中,类有一个ostream-operator,它应该能够将类Example写入ostream:
#include <iostream>
using namespace std;
template<class T>
class Example
{
public:
Example(T a) : x(a){}
std::ostream& operator << (std::ostream& os) const { os << x; }
private:
T x;
};
int main()
{
Example<int> test(5);
std::cout<<"test: "<<test<<std::endl;
return 0;
}
然而编译器抱怨:
prog.cpp: In function ‘int main()’:
prog.cpp:17:21: error: no match for ‘operator<<’ (operand types are ‘std::basic_ostream<char>’ and ‘Example<int>’)
std::cout<<"test: "<<test<<std::endl;
~~~~~~~~~~~~~~~~~~~^~~~~~
我知道如何通过在类外定义运算符&lt;&lt;(osteam,Example)来解决这个问题,但我很困惑为什么会员版本不起作用?
问题:为什么operator<<
没有匹配?