C++模板模板

Tho*_*mer 4 c++ templates

我试图通过实现通用容器类来理解C++模板模板.这是代码:

    using namespace std;

    template <typename T, template <typename STORETYPE> class Container>
    class Store {
    public:
        ~Store() {};
        Store() {};
        void someFunc( const T & ) {};
        //...
    private:
        Container<T> storage;
    };




    int main(int argc, char *argv[])
    {
        Store<int,deque> myStore;   // error here, won't compile!
    }
Run Code Online (Sandbox Code Playgroud)

上面的代码生成编译器错误消息.错误消息是:

"模板模板参数具有与其对应的模板模板参数Store aStack1不同的模板参数;

我不知道为什么.怎么了?

Tar*_*ama 6

您的问题是std::deque(和其他标准容器)不只是采用单个模板参数.除了存储类型,您还可以指定要使用的分配器仿函数类型.

如果您不关心这些额外的参数,您可以采用可变参数模板模板并继续:

template <typename T, template <typename...> class Container>
//                             variadic ^^^
class Store {
Run Code Online (Sandbox Code Playgroud)

如果您还想支持将可选参数传递给容器类型,可以像这样转发它们:

template <template <typename ...> class Container, typename T, typename... ContainerArgs>
class Store {
    //...
    Container<T,ContainerArgs...> storage;
};
Run Code Online (Sandbox Code Playgroud)

然后实例化如下:

Store<deque,int> myStore;
Store<deque,int,MyIntAllocator> mySpecialStore;
Run Code Online (Sandbox Code Playgroud)

但是,您可能只想使用特化提取模板参数:

template <typename Container>
class Store;

template <template <typename...> class ContainerType, typename T, typename... OtherArgs>
class Store<ContainerType<T,OtherArgs...>>
{
    //...
};
Run Code Online (Sandbox Code Playgroud)

这将让客户端代码实例化如下:

Store<deque<int>> myStore;
Store<deque<int,MyIntAllocator>> mySpecialStore;
Store<T> myOtherStore; //where T is some specialized container type
Run Code Online (Sandbox Code Playgroud)