如何正确编写模板模板参数?

How do I write template template parameters correctly?

本文关键字:参数 何正确      更新时间:2023-10-16

我正在尝试使用模板为任何c++集合制作适配器。

我需要使用模板模板参数,所以我可以使用适配器:

CollectionAdapter<std::vector<int>> a;

而不是:

CollectionAdapter<std::vector<int>,int> a;

一次需要两个模板形参。

我写了这个类:

template <
    template <class U> class T
>
class CollectionAdapter {
public:
    typedef T<U> ThisCol;
    typedef void iterator;
    CollectionAdapter() {}
    bool add(ThisCol& c,const U& i);
    bool remove(ThisCol& c,const U& i);
    U& getByIndex(int i);
    ThisCol instantiate();
    iterator getIterator(ThisCol& c);
};

但是,visual studio编译器给我这个错误:

error C2065: 'U' : undeclared identifier

对于这行:

typedef T<U> ThisCol;

我做错了什么?

我认为你不需要模板模板参数。你可以简化你的代码:

template <class T>
class CollectionAdapter 
{
public:
    typedef T ThisCol;
    typedef typename T::value_type value_type;
    //typedef void iterator; // what?? did you mean void*?
    typedef void* void_iterator; // but not sure what the use of this is.
    // you might need the container's iterator types too
    typedef typename T::iterator iterator
    typedef typename T::const_iterator const_iterator

    CollectionAdapter() {}
    bool add(T& c,const value_type& i);
    bool remove(T& c,const value_type& i);
    value_type& getByIndex(int i);
    const value_type& getByIndex(int i) const;
    ThisCol instantiate();
    iterator getIterator(T& c);
};