使用Typedef指定模板参数

时间:2011-10-06 19:41:37

标签: c++ templates iterator c++11

我希望能够将两个连接的迭代器作为一个传递来利用一些类似stl的算法(例如TBB),所以我正在创建一个自定义迭代器来加入它们但是遇到了一些绊脚石。

我需要专门化迭代器,但它不会让我一般指定模板参数。

像这样:

template<typename IT1, typename IT2>
struct multi_iter : public std::iterator<
                            std::output_iterator_tag,
                            std::pair<IT1::value_type&, IT2::value_type&> >
{
.
:

然而,它会让我这样做,但这不是我追求的目标

template<typename IT1, typename IT2>
struct multi_iter : public std::iterator<
                            std::output_iterator_tag,
                            std::pair<int&, int&> >
{
.
:

我收到此错误

multi_iter.cpp:12:53: error: template argument 2 is invalid
multi_iter.cpp:12:55: error: template argument 2 is invalid
multi_iter.cpp:12:55: error: template argument 4 is invalid
multi_iter.cpp:12:55: error: template argument 5 is invalid
.
:

我确实有std :: pair

非常感谢任何帮助。

由于

3 个答案:

答案 0 :(得分:3)

value_typeIT1上的从属类型,因此您必须指定typename

typename IT1::value_type

答案 1 :(得分:1)

template<typename IT1, typename IT2>
struct multi_iter : public std::iterator<
                            std::output_iterator_tag,
                            std::pair<IT1::value_type&, IT2::value_type&> >

IT1::value_type依赖于类型参数而且是一种类型,因此需要通过typename关键字指定:

template<typename IT1, typename IT2>
struct multi_iter : public std::iterator<
                            std::output_iterator_tag,
                            std::pair<typename IT1::value_type&, typename IT2::value_type&> >

BTW如果你想“压缩”两个迭代器(即迭代两个序列{1,2}和{“a”,“b”},为(1,“a”),那么(2,“ b“)),查看zip_iterator库中的boost.iterators

答案 2 :(得分:1)

你试过这个吗?

template<typename IT1, typename IT2>
struct multi_iter : public std::iterator<
                            std::output_iterator_tag,
                            std::pair< typename IT1::value_type&, typename IT2::value_type& > >
{
.
: