C ++模板模板帮助 [英] Help with c++ template templates

查看:102
本文介绍了C ++模板模板帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Ok, so I wrote an stl-like algorithm called cartesian_product. For those who don't know, the cartesian product is every possible pair of elements from two sets. So the cartesian product of {1, 2, 3} and {10, 20, 30} is

{(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);
}

没有模板typedef,所以我制作了一个traits类来保存 输出迭代器来自:

There aren't template typedefs, so I made a traits class to hold the type that the output iterator is from:

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);

但这似乎无法编译.我收到一个不错的错误:

but this doesn't seem to compile. I get a nice error:

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

所以我很困惑.我如何使它工作?

So I'm stumped. How do I get this to work?

推荐答案

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

The template parameter list for vector isn't just one element, it takes two:

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

因此,为了接受矢量,您需要一个带有两个空格的模板template参数:

so in order to accept vector, you need to have a template template parameter with two blanks:

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

已编辑:削减了一些建议,误读了您的代码.

Edited: cut some advice, misread your code.

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

The way to do this properly would be to use a variadic macro on the template template parameter:

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

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

But that's far away from being a standard. If it were my code, I'd probably just have the consumers pound out the full template:

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

cartesian_product_traits<int, int, vector>

,而后者只有在笛卡尔积的定义发生变化的情况下才有用.

and the latter would only help if the definition for a Cartesian product changed.

这篇关于C ++模板模板帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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