简体   繁体   English

当我尝试在模板化 function 中使用迭代器时,“期望在 'typename' 之后有一个限定名称”

[英]“expected a qualified name after 'typename'” when I try to use iterator inside of a templated function

I want to make a function that takes a container T (can be vector, map, list...) as template and a T and a Int as arguments, in this function, we're assuming that T is a container of int, and I want to return the first occurence of the int in the container. I want to make a function that takes a container T (can be vector, map, list...) as template and a T and a Int as arguments, in this function, we're assuming that T is a container of int,我想返回容器中第一次出现的 int 。 Here's the function:这是 function:

template <class T> int & easyfind(T container, int n)
{
    typename T<int>::iterator it;

    for (it = container.begin(); it != container.end(); it++)
        if (*it == n)
            return (*it);
    throw (NotFoundException());
}

But the compiler says "expected a qualified name after 'typename'", and when I replace the typename by class the compiler says "explicit specialization of non-template class 'T'", how can I get this to work?但是编译器说“在'typename'之后需要一个限定名”,当我用class替换typename时,编译器说“非模板class'T'的显式专业化”,我怎样才能让它工作?

T is a type, not a template. T是一种类型,而不是模板。 You need你需要

typename T::iterator it;

to access its iterator type member.访问其iterator类型成员。

The reason you see code like您看到类似代码的原因

std::vector<int>::iterator

is because std::vector is the name of a template, and you need to specify the template parameter.是因为std::vector是模板的名字,需要指定模板参数。 In your case T is already an instantiation of a template, so there is no need to specify the parameter.在您的情况下, T已经是模板的实例化,因此无需指定参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM