テンプレートのクラスにoperator<<
を実装して、含まれるすべての要素を指定されたstd::ostream&
に印刷できるようにしたいと思います。問題は、私が定義した関数を認識させることができないということです。ネストされたプライベートクラスのコレクションを持つクラスのoperator <<を正しくオーバーロードするには?
私が手にエラーが理想的
error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'Outer<int>::Inner')
os << inner << ", ";
~~~^~~~~~~~
私はインライン定義された機能を持っていないたいと思いますが、私もそれがインラインで動作させることはできません。下のコードでは、クラス宣言の外側に定義しようとした私のコメントをコメントアウトしていることがわかります。上記と同じエラーが発生します。
This questionは、オペレータをクラスの友人にすることをお勧めします。私は考えているすべての方法でそれをやってきましたが、それはまだ動作しません。
コード:
#include <iostream>
template<class T>
class Outer {
class Inner {
T item;
template<class T_>
friend std::ostream& operator<<(std::ostream& os, const typename Outer<T_>::Inner& inner) {
os << inner.item;
return os;
}
template<class T_>
friend std::ostream& operator<<(std::ostream& os, const Outer<T_> outer);
};
std::vector<Inner> inner_items;
template<class T_>
friend std::ostream& operator<<(std::ostream& os, const Outer<T_> outer);
template<class T_>
friend std::ostream& operator<<(std::ostream& os, const typename Outer<T_>::Inner& bar);
};
/*template<class T>
std::ostream& operator<<(std::ostream& os, const typename Outer<T>::Inner& bar) {
os << inner.item;
return os;
}*/
template<class T>
std::ostream& operator<<(std::ostream& os, const Outer<T> outer) {
for (typename Outer<T>::Inner inner : outer.inner_items) {
os << inner << ", ";
}
return os;
}
int main()
{
Outer<int> outer;
std::cout << outer;
}
これは機能しますが、クラス宣言の外部の関数を定義することは可能ですか? –
@JonMcClung:http://ideone.com/WVUeWz – lorro