2016-06-24 3 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을 사용하는 시범 프로그램입니다. 나는 그것이 당신을 도울 수 있다고 생각합니다. 컴파일러는 IT라는 형태의 선언에 대한 현재 범위 (운영자 템플릿)에 보이는 템플릿 내부 IT을 사용하는 경우

#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 유형을 사용하려면 array<T,U>::IT을 사용하여 정규화해야합니다. 아니면 C++ 11을 사용하는 경우 auto을 시도해 볼 수 있습니다.

+0

@thank you! 너는 내 하루를 보냈다. –