c++ - 帮助 c++ 模板模板

标签 c++ templates template-templates

好的,所以我写了一个类似 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'

所以我很难过。我如何让它发挥作用?

最佳答案

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

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

所以为了接受 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>

而后者只有在笛卡尔积的定义发生变化时才有用。

关于c++ - 帮助 c++ 模板模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/979436/

相关文章:

c++ - 允许 tr1::function 吞下返回值的解决方法

c++ - 如何为模板类参数指定必需的继承?

c++ - 具有可变参数模板的功能组合

c++ - 未自动确定的模板化类型的隐式转换运算符

c++ - Variadic 可变模板模板参数

c++ - STL map 比较器能否以某种方式获得指向 map 本身的指针?

c++ - Opencv 的 image.empty() 函数不工作

php - block 和模板如何在 Magento 中工作

c++ - 成为模板模板参数的 friend