2016-06-24 37 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) 作爲數組結構的朋友?

回答

0

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

,並更改

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

typedef typename std::map<const Key, string>::const_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)to:上面的ostream&operator <<(ostream&os,const數組&var)。 –

+0

@OsagieOdigie默認情況下,如果沒有typename,編譯器會將該名稱視爲不是類型名稱。 –

0

當你使用IT您的模板編譯器會在當前範圍(操作模板)名爲IT類型的聲明中。

這會失敗,因爲您將該類型定義爲數組結構的一部分。

因此,要使用IT類型,您需要使用array<T,U>::IT完全限定它。 或者如果您使用C++ 11,則可以嘗試使用auto

+0

@謝謝你!你讓我很快樂。 –

相關問題