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

Ste*_*phQ 19 c++ templates stl metaprogramming

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

std::vector<double>::iterator i; //An iterator to a std::vector<double>
Run Code Online (Sandbox Code Playgroud)

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

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

ContainerOf< std::vector<double>::iterator >::type 
Run Code Online (Sandbox Code Playgroud)

评估为

std::vector<double>
Run Code Online (Sandbox Code Playgroud)

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

预先感谢您的任何帮助!

Hit*_*bat 9

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

  • 如果结构`std::iterator_traits&lt;T&gt;` 有`typedef T container_type;` 是可能的,但是你可以用这样的typedef 制作你自己的`std::iterator_traits_pro`。 (2认同)

Éri*_*ant 6

只是为了好玩,这里有一些我很快就用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;
}
Run Code Online (Sandbox Code Playgroud)