简体   繁体   English

声明采用模板参数的函数

[英]declaring functions that take template parameters

I want to define a helper function that takes a template parameter. 我想定义一个带有模板参数的辅助函数。 I have tried making a templated function for this, but it does not compile. 我尝试为此创建模板化函数,但无法编译。 Any idea what I'm doing wrong? 知道我在做什么错吗? Here's the code I tried. 这是我尝试的代码。

// vectors are great, but lack a find method. Implement one as a helper.
template<class T> bool vec_find(vector<T> &v, T obj)
{
    vector<T>::iterator s;
    for (s = v.begin(); s < v.end(); s++)
    {
        if (*s == obj)
        {
            return true;
        }
    }
    return false;
}

Presumably, your compiler told you what the problem was. 据推测,您的编译器告诉您问题出在哪里。 Mine said: 我的说:

test.cpp:7:5: error: need ‘typename’ before ‘std::vector<T>::iterator’ because ‘std::vector<T>’ is a dependent scope

So to fix it, add typename before vector<T>::iterator : 因此,要解决此问题,请在vector<T>::iterator之前添加typename

typename vector<T>::iterator s;
^^^^^^^^

In general, you need that whenever the scope of a type name depends on a template parameter; 通常,只要类型名称的范围取决于模板参数,就需要使用它。 until the template is instantiated, the compiler doesn't know how vector<T> will be defined, and so needs to be told that a name scoped inside it refers to a type rather than something else. 在实例化模板之前,编译器不知道vector<T>定义方式,因此需要告知其内部作用域的名称是指类型,而不是其他名称。

However, there is a good reason why vector doesn't have a find method: the C++ library separates containers from the algorithms that act on them, so that any algorithm can act on any suitable sequence. 但是, vector没有find方法的原因很充分:C ++库将容器与作用于容器的算法分开,以便任何算法都可以作用于任何合适的序列。 You want to use std::find for this: 您想为此使用std::find

return std::find(v.begin(), v.end(), obj) != v.end();

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

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