以下のコードには、メンバータイプ(struct Element)のテンプレートクラスがあります。そのメンバータイプのoperator <<をオーバーロードしたい。ただし、コードはコンパイルされません。
誰かが私がどこで間違っているのか指摘できれば幸いです。
include <iostream>
using namespace std;
// fwd decl
template<class T> class CC;
// operator<< overload template for member type CC<T>::Element
template<class T>
ostream& operator<<(ostream& os, const typename CC<T>::Element& elm) {
return os << elm.val1 << "/" << elm.val2;
}
template<class T>
class CC
{
public:
struct Element { // type member
int val1;
int val2;
};
template<typename U>
friend ostream& operator<<(ostream& os, const typename CC<U>::Element& elm);
};
int main() {
CC<int>::Element elm{0,0};
cout << elm << endl; // does not compile due to this!
}
テンプレートの引数は、ネストされたエンティティから推測することはできません(簡単な説明:タイプは、さまざまなテンプレートのインスタンス化の継ぎ目である可能性があります)。つまり、宣言
template<typename U>
ostream& operator<<(ostream& os, const typename CC<U>::Element& elm);
friend
型U
を推測できないため、aの有無は考慮されません。friend
演算子を非テンプレートにすることで、問題を修正できます。
// ...
friend ostream& operator<<(ostream& os, const Element& elm) { ... }
// or
friend ostream& operator<<(ostream& os, const CC<T>::Element& elm) { ... }
// ...
ただし、関数はその宣言で実装する必要があります。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加