模板模板参数不起作用

template template parameters not working

本文关键字:不起作用 参数      更新时间:2023-10-16

我有以下类:

    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++》一书的第一章,其中也有类似的内容。问题出在哪里?非常感谢。

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

 algorithmType <dataType, heapType> myAlgorithm;

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

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

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

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

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

问题是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 {...};