在特定类型的元素的任何容器上采用STL迭代器的函数 [英] Function that takes an STL iterator over ANY container of a elements of a specific type

查看:122
本文介绍了在特定类型的元素的任何容器上采用STL迭代器的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何定义一个函数作为输入在任何类型的STL容器,但只有特定模板类型的迭代器。例如:

How would I define a function that takes as input an iterator over any type of STL container, but only to those of a specific templated type. For example:

任何形式的迭代器 std :: list< Unit *> :: iterator std :: vector< Unit *> :: iterator

Any iterator of the form std::list<Unit*>::iterator or std::vector<Unit*>::iterator

该函数取 std :: list< Unit *> :: iterator ,但如果我们切换到不同的STL容器,我不想改变我的

I would just define the function to take std::list<Unit*>::iterator, but if we switch to a different STL container, I don't want to have to change my code.

推荐答案

您可以使用 SFINAE 结构,例如boost::enable_if ,用于验证嵌套的typedef iterator :: value_type 是否确实是

You could use a SFINAE construct such as boost::enable_if which verifies if the nested typedef iterator::value_type is indeed of the appropriate type.

template<class T, class Iterator>
typename boost::enable_if<boost::is_same<typename Iterator::value_type, T> >::type
    f(Iterator i)
{
    /* ... */
}

int main()
{
    std::list<int> l;
    std::vector<int> v;

    f<int>(l.begin()); // OK
    f<int>(v.begin()); // OK

    std::vector<float> v2;
    f<int>(v2.begin()); /* Illegal */
}

这是我从作为输入一个迭代器在任何类型的STL容器,但只有那些特定的模板类型,但我的解释可能是错误的。

This is what I understand from "a function that takes as input an iterator over any type of STL container, but only to those of a specific templated type", but my interpretation might be wrong.

这篇关于在特定类型的元素的任何容器上采用STL迭代器的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆