我可以使用std :: vector作为模板参数,还是需要std :: vector <T>?

Xav*_*ier 5 c++ templates

我知道这是一个简单的问题,但我找不到答案.

我试图做这样的事情,但最终我希望它是std :: shared_ptr或std :: weak_ptr而不是std :: vector.

template <int dim, class ChunkClass, class PtrClass>
class BaseChunkWindow : public IChunkWindow<BaseChunkWindow<dim, ChunkClass, PtrClass>, IChunk<ChunkClass>> {
public:
...
private:
PtrClass< IChunk<ChunkClass> > ptr;  <-- compiler doesn't like this line, however IChunk<ChunkClass>* works
};
Run Code Online (Sandbox Code Playgroud)

Sir*_*Guy 13

这取决于你传递给它的是什么,如果你试图实例化的模板将一个类模板作为参数接受2(或在c ++ 11中有一个可变数量的)类,那么你可以将std :: vector传递给那.但是,在大多数情况下,模板需要类作为参数,并且您无法传递类模板std :: vector.

    template <class T>
    struct gimme_a_type{};

    template <template <class,class> class T>
    struct gimme_a_template{};

    gimme_a_type<std::vector> //<-- does not compile, expected a type, got a template
    gimme_a_type<std::vector<int> > //<-- compiles, expected a type, got a type
    gimme_a_template<std::vector> //<-- compiles, expected a template, got a template that has the correct signature
    gimme_a_template<std::vector<int> > //<-- does not compile, expected a template, got a type
Run Code Online (Sandbox Code Playgroud)

为了响应您的编辑,使用类模板作为模板参数存在困难.在您尝试传递的类模板中有默认参数时,实际上很难匹配参数的数量(std::vector在我们的例子中).请注意,上面的示例需要一个类模板,它需要2个类,而不只是一个.这是因为std::vector需要两个参数,第二个参数只是默认std::allocator<T>为我们.

以下示例演示了此问题:

    template <template <class, class> class Tem>
    struct A
    {
        Tem<int> v; //<-- fails to compile on gcc, Tem takes two parameters
        Tem<int, std::allocator<int> >; //<-- compiles, but requires a priori knowledge of Tem
    };

    template <template <class...> class Tem>
    struct A2
    {
      Tem<int> v; //<-- This C++11 example will work, but still isn't perfect.
    };
Run Code Online (Sandbox Code Playgroud)

C++ 11的例子更好,但是如果有人传递了一个作为签名的类,template <class, bool = false> class A3它会再次失败,因为A2需要一个可变数量的类,而不是一个可变数量的whatevers.因此即使A3<int>可能是有效的实例化,也无法将该类传递给A2.
解决方案是始终在模板参数列表中使用类型,并使用std::integral_constant包装器模板来传递整数常量.


Rap*_*ptz 5

有几种方法可以做到这一点.

有限的方法是使用模板模板参数,只传递有限数量的参数,例如3.

template<template<class,class,class> class Cont, class T, class V, class U>
void f(Cont<T,V,U>&& cont) {
    //...
}
Run Code Online (Sandbox Code Playgroud)

然而,这是非常有限的,如果你决定在将来改变它,可能很难管理.

所以你可以使用C++ 11中的新Variadic模板这样做:

template<template<class...> class Cont, typename F, typename... Rest>
void f(Cont<F, Rest...>&& cont) {
    //...
}
Run Code Online (Sandbox Code Playgroud)

这适用于其他容器或东西,可能更容易管理.