T :: iterator出错,其中模板参数T可能是vector <int>或list <int>

bre*_*ert 6 c++ templates stl repr

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

vector<int> v(10, 0);
repr< vector<int> >(v);
Run Code Online (Sandbox Code Playgroud)

...

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";
}
Run Code Online (Sandbox Code Playgroud)

...

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
Run Code Online (Sandbox Code Playgroud)

我尝试了'typename T :: iterator',但是只有一个更加神秘的错误.

编辑:谢谢你的帮助!这是一个适合想要使用此功能的人的工作版本:

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";
}
Run Code Online (Sandbox Code Playgroud)

sel*_*tze 18

您需要typename告诉编译器::iterator应该是一个类型.编译器不知道它是一个类型,因为在实例化模板之前它不知道T是什么.例如,它还可以引用一些静态数据成员.那是你的第一个错误.

你的第二个错误是constv -reference- const.所以,而不是::iterator你必须使用::const_iterator.你不能要求一个常量容器用于非const迭代器.

  • @visitor:使用正确的两阶段实现(读取"非MSVC"),编译器无法知道第一遍中的"迭代器"是什么,因为模板参数尚未设置.参见例如项目6和7 [这里](http://womble.decadent.org.uk/c++/template-faq.html#disambiguation). (3认同)
  • 我知道了.因此,这种头发分裂证明了一个downvote. (2认同)