运算符<<不能使用其好友数组的 IT 成员

operator<< cannot use an IT member of its friend, array

本文关键字:lt 数组 成员 好友 IT 不能 运算符      更新时间:2023-10-16

我想,如果我制作运营商&lt;&lt;的朋友数据结构(名称数组);

//Forward Declarations
template<typename S, typename T> 
struct array;
template<typename U, typename V>
ostream& operator<< (ostream& ous, const array<U, V>& t);

那么,我将能够做这样的事情;在实施操作员的实施中&lt;

//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
}

问题:我到底在做什么错,或者,为什么我无法直接访问和使用即使我宣布运算符&lt;&lt;(要求它)作为数组结构的朋友?

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

和更改

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

to

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 

在模板中使用IT时,编译器在当前范围(操作员模板)中查看一种名为IT的类型。

这失败了,因为您将类型定义为数组结构的一部分。

因此,为了使用IT类型,您需要使用array<T,U>::IT充分限定它。或者,如果您使用C 11。

,则可以尝试auto