未在模板化函数/类中使用stl容器

Dae*_*all 2 c++ templates stl

当我尝试编译以下代码时......

#include <vector>

template <class T> void DoNothing()
{
    std::vector<T>::iterator it;
}

int main(int argc, char**argv)
{
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

g ++说:

test.cpp:5:错误:预期`;' 在'它'之前

我不明白为什么这是一个问题.如果我用它替换它std::vector<int>::iterator,比如,它按预期工作正常.

你可以看到我没有实例化这个函数,所以g ++必须有模板定义本身的问题,但我看不出它是如何无效的.

感谢您提供有关最新情况的任何建议.

NB我实际上是在尝试编写模板化的类并且遇到地图而不是向量的问题,但这是我问题的最简单的测试用例.

Mic*_*urr 7

您需要使用typename关键字,因为std::vector<T>::iterator类型取决于模板参数:

template <class T> void DoNothing()
{
    typename std::vector<T>::iterator it;
}
Run Code Online (Sandbox Code Playgroud)

当您需要使用它时typename以及当您不需要它时(或者甚至不允许使用它)时,它实际上可能会令人困惑.这篇文章有一个很好的概述: