【发布时间】:2011-07-04 07:44:50
【问题描述】:
这个编译和工作正常(非嵌套模板):
#include <iostream>
template<typename T> class Z;
template <typename T>
std::ostream& operator<< (std::ostream& os, const Z<T>&) {
return (os << "Z");
}
template<typename T> class Z {
friend std::ostream& operator<< <> (std::ostream& os, const Z&);
};
int main () {
Z<int> z;
std::cout << z << std::endl;
}
这个不能编译(gcc 4.4 和 gcc 4.6,在 03 和 0x 模式下):
#include <iostream>
template<typename T> class Z;
template<typename T>
std::ostream& operator<< (std::ostream& os, const typename Z<T>::ZZ&) {
return (os << "ZZ!");
}
template <typename T> class Z {
public:
class ZZ {
friend std::ostream& operator<< <> (std::ostream& os, const ZZ&);
};
};
int main () {
Z<int>::ZZ zz;
std::cout << zz << std::endl;
}
错误信息如下所示:
error: template-id ‘operator<< <>’ for ‘std::ostream& operator<<(std::ostream&,
const Z<int>::ZZ&)’ does not match any template declaration
error: no match for ‘operator<<’ in ‘std::cout << zz’
0x模式下第二条错误信息不同,但含义相同。
有没有可能做我想做的事?
EDIT 显然,这里有一个 non-deduced context 的实例,它解释了错误消息。然而,问题仍然存在:我可以为嵌套在类模板中的类提供一个有效的 operator<< 吗?
【问题讨论】:
-
我正在处理它...您可以通过添加“运算符 ”来消除第一个错误,这也使事情更具可读性。
-
@Matthieu:我很想看看那个链接中的代码适应了这个问题。可以把它作为像我这样的“普通凡人”(可能还有“n.m.”)的答案吗? ;-)
-
您始终可以使用朋友声明正确地实现它。 (是的,我假设您期望得到更好的答案,但我很想知道需要做什么)
-
这里已经讨论过同样的问题stackoverflow.com/questions/4092237/…