本文介绍了T :: iterator的错误,其中模板参数T可以是向量< int>或list< int>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个函数来打印常见STL容器(向量,列表等)的表示。我给函数一个模板参数T,例如,它可能表示向量。我在获取类型T的迭代器时遇到问题。

I'm trying to write a function to print a representation of common STL containers (vector, list, etc..). I gave the function a template parameter T which, for example, might represent vector. I'm having problems getting an iterator of type T.

vector<int> v(10, 0);
repr< vector<int> >(v);

...

template <typename T>
void repr(const T & v)
{
    cout << "[";
    if (!v.empty())
    {
        cout << ' ';
        T::iterator i;
        for (i = v.begin();
             i != v.end()-1;
             ++i)
        {
            cout << *i << ", ";
        }
        cout << *(++i) << ' ';
    }
    cout << "]\n";
}

...

brett@brett-laptop:~/Desktop/stl$ g++ -Wall main.cpp
main.cpp: In function ‘void repr(const T&)’:
main.cpp:13: error: expected ‘;’ before ‘i’
main.cpp:14: error: ‘i’ was not declared in this scope
main.cpp: In function ‘void repr(const T&) [with T = std::vector<int, std::allocator<int> >]’:
main.cpp:33:   instantiated from here
main.cpp:13: error: dependent-name ‘T::iterator’ is parsed as a non-type, but instantiation yields a type
main.cpp:13: note: say ‘typename T::iterator’ if a type is meant

我尝试'typename T :: iterator'作为编译器建议,但只有一个更加神秘的错误。

I tried 'typename T::iterator' as the compiler suggested, but only got a more cryptic error.

编辑:感谢帮助家伙!这是一个工作版本的任何人谁想要使用这个功能:

Thanks for the help guys! Here's a working version for anyone who wants to use this function:

template <typename T>
void repr(const T & v)
{
    cout << "[";
    if (!v.empty())
    {
        cout << ' ';
        typename T::const_iterator i;
        for (i = v.begin();
             i != v.end();
             ++i)
        {
            if (i != v.begin())
            {
                cout << ", ";
            }
            cout << *i;
        }
        cout << ' ';
    }
    cout << "]\n";
}


推荐答案

c> typename 告诉编译器 :: iterator 应该是一个类型。编译器不知道它是一个类型,因为它不知道什么T是,直到你实例化模板。例如,它也可以引用一些静态数据成员。这是你的第一个错误。

You need typename to tell the compiler that ::iterator is supposed to be a type. The compiler doesn't know that it's a type because it doesn't know what T is until you instantiate the template. It could also refer to some static data member, for example. That's your first error.

你的第二个错误是 v 是一个引用。所以,你必须使用 :: const_iterator ,而不是 :: iterator 。你不能为一个非常量的迭代器请求一个常量容器。

Your second error is that v is a reference-to-const. So, instead of ::iterator you have to use ::const_iterator. You can't ask a constant container for a non-const iterator.

这篇关于T :: iterator的错误,其中模板参数T可以是向量&lt; int&gt;或list&lt; int&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 02:19