繁体   English   中英

从C ++(STL)中的(it)迭代器类型获取容器类型

[英]Obtain container type from (its) iterator type in C++ (STL)

给定一个容器来获取相关的迭代器很容易,例如:

std::vector<double>::iterator i; //An iterator to a std::vector<double>

我想知道在给定迭代器类型的情况下是否有可能推导出“相应容器”的类型(这里我假设每个容器都有一个且只有一个(非常量)迭代器)。

更准确地说,我想要一个适用于所有STL容器的模板元函数(无需为每个单个容器手动专门化),例如:

ContainerOf< std::vector<double>::iterator >::type 

评估为

std::vector<double>

可能吗? 如果没有,为什么?

预先感谢您的任何帮助!

我不认为这是可能的。 在一些STL库中,你实际上有一个向量迭代器作为指针类型, ie std::vector<T>::iterator is a T*所以我想不出你可以从那里回到容器类型的任何方式。

只是为了好玩,这里有一些我很快就用Boost.MPL攻击的东西(警告:这是表面上经过测试的,所以小心处理):

#include <boost/mpl/list.hpp>
#include <boost/mpl/find_if.hpp>
#include <boost/type_traits.hpp>
#include <vector>
#include <string>
#include <list>
#include <set>

// List of candidate container types
template<typename T>
struct ContainersOf : boost::mpl::list<
    std::vector<T>,
    std::basic_string<T>,
    std::list<T>,
    std::set<T>
>{};

// Metafunction to evaluate if IteratorT == ContainerT::iterator
template<class IteratorT, class ContainerT>
struct IsIteratorOf
{
    typedef typename 
    boost::is_same<
        IteratorT, 
        typename ContainerT::iterator
    >::type type;
};

// Metafunction to compute a container type from an iterator type
template<class IteratorT>
struct ContainerOf
{
    typedef typename 
    boost::mpl::deref<typename 
        boost::mpl::find_if<
            ContainersOf<typename std::iterator_traits<IteratorT>::value_type>,
            IsIteratorOf<IteratorT, boost::mpl::_1>
        >::type
    >::type type;
};

// Test
int main()
{
    ContainerOf<std::list<int>::iterator>::type l;
    std::list<int> l2 = l;  // OK
    std::vector<int> v = l; // Fails to compile

    return 0;
}

C ++ STL迭代器的确切运行时类型是故意未定义的,因此是特定于实现的。 您可以搜索编译器供应商的头文件以找出实际使用的类型并从中推断出容器,但它是特定于供应商和版本的,因此容易出现问题。

迭代器的意思是你使用它们来做工作而不必知道底层容器类型,例如传递一个开始/结束对并在该范围上工作。

但是,如果您关心的只是迭代器类型,我相信您可以使用迭代器特征来确定迭代器是否是随机访问。 std::advance为例,一般情况是它在迭代器上调用operator++ n次,但是专门用于随机访问迭代器而不是使用+ =。

除此之外,我不知道从迭代器获取容器类型的任何方法。

暂无
暂无

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

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