[英]Explicit specialization of friend function for a class template
我正在阅读 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);
}
在 litb 的示例中,他只是将专业化声明为班级中的朋友。 他没有定义专业化,这就是您的代码所做的。 不允许在类声明(或任何非命名空间范围)中定义特化。
你需要的是这样的:
template <class T>
class foo;
template<class T>
std::ostream& operator<<(std::ostream& os, const foo<T>& f)
{
return os << "val=" << f._val;
}
template<typename T>
struct foo
{
// ...
private:
friend std::ostream& operator<< <>(std::ostream& os, const foo<T>& f);
T _val;
};
您有 2 个选择:
删除 fwd 声明并在类中定义所有内容。
例子
template <typename U>
friend std::ostream& operator<<(std::ostream& os, const foo<U>& f) // this works
{
return os << "val=" << f._val;
}
在类之外定义友元函数。
例子
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);
T _val;
};
template <typename T>
std::ostream& operator<<(std::ostream& os, const foo<T>& f)
{
return os << "val=" << f._val;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.