我在这里阅读了 litb 对一个问题的回答,他详细说明了如何创建类模板的专用友元函数。
我试图创建一个符合他建议的示例(最后的代码):
// use '<>' to specialize the function template with the class template's type
friend std::ostream& operator<< <>(std::ostream& os, const foo<T>& f)
它会导致编译器错误:
error: defining explicit specialization ‘operator<< <>’ in friend declaration
在特化中显式声明模板参数也不起作用:
friend std::ostream& operator<< <T>(std::ostream& os, const foo<T>& f) // same error
另一方面,从使用特化改为使用友元函数模板确实有效:
template<typename U>
friend std::ostream& operator<<(std::ostream& os, const foo<U>& f) // this works
所以我的问题是:
- 是什么导致了第一个错误?
- 我怎样才能明确地专门
ostream operator
化周围的类模板专业化?
下面的示例代码:
#include <iostream>
// fwd declarations
template<typename T> struct foo;
template<typename T> std::ostream& operator<<(std::ostream&, const foo<T>&);
template<typename T>
struct foo
{
foo(T val)
: _val(val)
{}
friend std::ostream& operator<< <>(std::ostream& os, const foo<T>& f) // error line
//template<typename U>
//friend std::ostream& operator<<(std::ostream& os, const foo<U>& f) // this works
{
return os << "val=" << f._val;
}
T _val;
};
int main()
{
foo<std::string> f("hello world");
std::cout << f << std::endl;
exit(0);
}