模板模板参数不起作用

时间:2014-04-10 16:17:30

标签: c++ templates

我有以下课程:

    template <class T, size_t dims> class dataType { ... };

    class heapType {...}; // Not templated so far.

    class dataClass {....};

这两个班级正常运作。现在我想做以下事情:

    template < template <class T, size_t dims> class data_t, class heap_t> algorithmType {...};

目标是将algorithmType与其他类一起用作策略:

    algorithmType <dataType<dataClass,2>, heapType> myAlgorithm;

但这会引发以下错误:

    error: ‘myAlgorithm’ was not declared in this scope
    algorithmType <dataType<dataClass,2>, heapType> myAlgorithm;
    ^

    error: expected primary-expression before ‘,’ token
    algorithmType <dataType<dataClass,2>, heapType> myAlgorithm;
                                        ^
    error: expected primary-expression before ‘>’ token
    algorithmType <dataType<dataClass,2>, heapType> myAlgorithm;
                                                  ^
    error: ‘myAlgorithm’ was not declared in this scope
    algorithmType <dataType<dataClass,2>, heapType> myAlgorithm;

我正在关注现代C ++书籍的第一章,其中有类似的东西。 问题出在哪儿?谢谢!

2 个答案:

答案 0 :(得分:2)

您正在声明模板模板参数,但您正在传递类型,而不是模板。更改用途并传入模板:

 algorithmType <dataType, heapType> myAlgorithm;

或者更改声明以接受类型:

template < class data_t, class heap_t> algorithmType {...};

哪一个取决于您的预期用途。

如果algorithmType只想要传入一个类,请将其更改为具有模板类型的参数,然后传递类dataType<dataClass,2>,就像您现在所做的那样。从模板中实例化类并不重要,它是类。

另一方面,如果您希望algorithmType能够为其输入模板参数提供自己的模板参数,请将其保留为模板模板参数,然后只传递模板。

答案 1 :(得分:1)

问题是algorithmType期望模板类接受type和int作为第一个参数,并且您传递的是具体类型。

更简单一点,这是定义该变量的正确方法:

algorithmType <dataType, heapType> myAlgorithm;

从评论中我看到你不明白模板类作为模板参数意味着什么。

下一个示例编译,并显示如何使用模板类作为模板参数:

#include <list>
#include <vector>

template< template < class, class > class V >
struct A
{
    V< int, std::allocator<int> > container;
};



int main()
{
    A< std::vector > a1;  // container is std::vector<int>
    A< std::list > a2;    // container is std::map<int>
}

如果需要传递具体类型,请将algorithmType更改为:

template class data_t, class heap_t> algorithmType {...};