我怎样才能让它发挥作用?我想在这里将friend ostream 函数的定义和声明分开。
#include <bits/stdc++.h>
using namespace std;
template <class T>
struct Outer {
struct Inner {
T x;
};
friend std::ostream& operator<<(std::ostream&, const Inner&);
};
template <class T>
std::ostream& operator<<(std::ostream& os, const Outer<T>::Inner& i) {
os << "x! " << i.x;
return os;
}
int main() {
const Outer<int>::Inner s = {42};
std::cout << s << "\n";
return 0;
}
按照错误的建议添加类型名也不起作用
template <class T>
std::ostream& operator<<(std::ostream& os, const typename Outer<T>::Inner& i) {
os << "x! " << i.x;
return os;
}
warning: friend declaration 'std::ostream& operator<<(std::ostream&, const Outer<T>::Inner&)' declares a non-template function [-Wnon-template-friend]
10 | friend std::ostream& operator<<(std::ostream&, const Inner&);
| ^
<source>:10:64: note: (if this is not what you intended, make sure the function template has already been declared and add '<>' after the function name here)
/opt/compiler-explorer/gcc-13.2.0/bin/../lib/gcc/x86_64-linux-gnu/13.2.0/../../../../x86_64-linux-gnu/bin/ld: /tmp/ccBSBhtj.o: in function `main':
<source>:24: undefined reference to `operator<<(std::ostream&, Outer<int>::Inner const&)'
collect2: error: ld returned 1 exit status
与:
template <class T>
std::ostream& operator<<(std::ostream& os, const typename Outer<T>::Inner& i)
T
不可推论。
将声明与定义分开并不明显。
会更简单
template <class T>
struct Outer {
struct Inner {
T x;
friend std::ostream& operator<<(std::ostream&, const Inner&) {
return os << "x! " << i.x;
}
};
};