2

好的,所以我写了一个类似 stl 的算法,叫做cartesian_product. 对于那些不知道的人,笛卡尔积是两组中所有可能的元素对。{1, 2, 3}所以和的笛卡尔积{10, 20, 30}

{(1,10), (1,20), (1,30), (2,10), (2,20), (2,30), (3,10), (3,20), (3,30)}

所以函数看起来像

template <typename InIt1, typename InIt2, typename OutIt>
void
cartesian_product(InIt1 first1, InIt1 last1, InIt2 first2, InIt2 last2, OutIt out)
{
    for (; first1 != last1; ++first1)
        for (InIt2 it = first2; it != last2; ++it)
            *out++ = std::make_pair(*first1, *it);
}

没有模板类型定义,所以我创建了一个特征类来保存输出迭代器的类型:

template <typename ObjA, typename ObjB, template <typename> class Container>
struct cartesian_product_traits
{
    typedef Container<std::pair<ObjA, ObjB> > type;
};

那么我可以说:

typedef cartesian_product_traits<int, int, std::vector>::type IntPairList;
IntPairList my_list;
cartesian_product(v1.begin(), v1.end(), 
                  v2.begin(), v2.end(),
                  std::back_inserter(my_list);

但这似乎无法编译。我得到一个很好的错误:

error C3201: the template parameter list for class template 'std::vector' does not match the template parameter list for template parameter 'Container'

所以我很难过。我怎样才能让它工作?

4

2 回答 2

8

vector 的模板参数列表不只是一个元素,它需要两个元素:

template < class T, class Allocator = allocator<T> > class vector

所以为了接受向量,你需要有一个带有两个空格的模板模板参数:

template <typename ObjA, typename ObjB, template <typename, typename> class Container>
struct cartesian_product_traits

编辑:删减一些建议,误读您的代码。

正确执行此操作的方法是在模板模板参数上使用可变参数宏:

template <typename ObjA, typename ObjB, template <typename ...> class Container>
struct cartesian_product_traits

但这远不是一个标准。如果是我的代码,我可能会让消费者敲出完整的模板:

std::vector< std::pair<int, int> >

短于

cartesian_product_traits<int, int, vector>

只有在笛卡尔积的定义发生变化时,后者才会有所帮助。

于 2009-06-11T05:28:35.557 回答
2

std::vector的模板实际上相当复杂(分配器和 c 具有可选的模板参数)——stdlib 中的其他容器也不简单。在你的鞋子里,我会把第三个参数cartesian_product_traits变成一个普通的typename PairsContainer,并依靠调用者去解决将它作为合适的成对容器传递的小麻烦。

于 2009-06-11T05:28:43.590 回答