2016-06-24 9 views
2

私はオペレータを作った場合、 <の友人の のデータ構造体(名前で配列);演算子<<その友人のITメンバーを使用することはできません、配列

//Forward Declarations 
template<typename S, typename T> 
struct array; 

template<typename U, typename V> 
ostream& operator<< (ostream& ous, const array<U, V>& t); 

次に、私はこのようなことをすることができます。オペレータ今< <

//operator<< is a friend of struct array{} already 
template<typename T, typename U> 
ostream& operator<< (ostream& os, const array<T, U>& var){ 

    if(var){ 
     /*Error: 'IT' was not declared in this scope*/ 

     for(IT it = var.data.begin(); it != var.data.end(); it++){ 
      /*and i thought i need not redeclare IT before using it 
      since operator<< is a friend of array already*/ 
     } 
    } 
    else{cout << "empty";} 

    return os; 
} 

の実装内で、ここでは、アレイの実装は次のとおりです。私はこのようにそれをテスト運転したとき

/*explicit (full) specialization of array for <type, char>*/ 
template<> 
template<typename Key> 
struct array<Key, char>{ 

    //data members 
    map<const Key, string> data; 
    typedef map<const Key, string>::iterator IT; 

    //member function 
    friend ostream& operator<< <>(ostream& ous, const array& t); 

    //other stuff/functions 
}; 

は最後に、コンパイラが怒っています。

void Test(){ 
    array<int, char> out; 
    out[1] = "one";   //Never mind. this has been taken care of 
    out[2] = "two";    
    cout << out;    //Error: 'IT' was not declared in this scope 
} 

質問: はまさに私が間違っているのか、なぜ私はdirrectlyアクセスできず、私は(ITを要求)オペレータ< <を宣言した後でさえ、 IT(アレイ内のtypedef)を使用します配列構造体のフレンドとして ?

答えて

0

書き込み

for(typename array<T, U>::IT it = var.data.begin(); it != var.data.end(); it++){ 

そして、ここで

typedef typename std::map<const Key, string>::const_iterator IT; 

typedef map<const Key, string>::iterator IT; 

を変更するには、代わりにstd::mapの私は簡単にするためstd::arrayを使用し実証するプログラムです。私はそれがあなたを助けることができると思います。

#include <iostream> 
#include <array> 

template <typename T, size_t N> 
struct A 
{ 
    std::array<T, N> a; 

    typedef typename std::array<T, N>::const_iterator IT; 
}; 

template <typename T, size_t N> 
std::ostream & operator <<(std::ostream &os, const A<T, N> &a) 
{ 
    for (typename A<T, N>::IT it = a.a.begin(); it != a.a.end(); ++it) os << *it << ' '; 

    return os; 
} 

int main() 
{ 
    A<int, 10> a = { { { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } } }; 

    std::cout << a << std::endl; 

    return 0; 
} 

プログラムの出力は

0 1 2 3 4 5 6 7 8 9 
+0

ありがとうございます!しかし、私は何が起こっているのか理解する必要があった。私も編集しました:ostream&operator <<(ostream&os、const _Tarray &var):ostream&operator <<(ostream&os、const配列&var) –

+0

@OsagieOdigieデフォルトではtypenameなしでは、コンパイラはその名前を型名ではないとみなします。 –

0

あなたは、テンプレート内のITを使用している場合は、コンパイラはITという名前の型の宣言のために現在のスコープ(オペレータテンプレート)に見えています。

型を配列構造体の一部として定義したため、これは失敗します。

ITタイプを使用するには、array<T,U>::ITを使用して完全修飾する必要があります。 または、C++ 11を使用している場合は、代わりにautoを試すことができます。

+0

@thank you!あなたのおかげで幸せになれた。 –

関連する問題