简体   繁体   中英

C++ template class inheriting from a template class

I try to have a partially specialized template class inheriting from another template class. I'm not sure how to to that. Here is my code:

template < typename T>
struct SmallContainer
{
    typedef vector<T> type;
};

template<typename CONTAINER, typename T>
class AnotherClass : public CONTAINER<SmallContainer<T>::type>
{ // ..... };

and gcc keeps saying expected template-name before '<' token expected '{' before '<' token expected unqualified-id before '<' token

The idea of my object is to have AnotherClass be a generic container of vector of any other type I want.

I tried to do template< template CONTAINER, typename T> etc... without any success. Any idea ? Thanks...

The usual way to let the user specify a container is by taking the actual container class as a template parameter, not just a container template. This is how the standard library specifies container adaptors, too. For example:

template <typename T, typename Container = std::vector<T>>
class Foo
{
public:
    typedef Container container_type;

    void multiply_all()
    {
        using std::begin;
        using std::end;

        for (auto it(begin(c)), e(end(c)); it != e; ++it)
        {
            *it = *it + *it;
        }
    }

private:
    container_type c;
};

Now the user can create other instances like Foo<int, CrazyContainer<int, true, Blue>> x; , and you never need to worry about the details of their container.

This would work for a container of just one template argument:

template< template< typename > class Container, typename T >
class AnotherClass
  : public Container< typename SmallContainer< T >::type >
{};

This, however, won't work for any of the standard containers as they have extra template arguments (like allocator).

Note that typename is needed before SmallContainer< T >::type or otherwise the compiler will assume it refers to a value.

This can't really be done, not with STL containers anyway. You could create a wrapper like SmallContainer for every container so that you can provide for the default arguments, but the STL containers don't share common arguments for the most part. Further there'd be no way to match third-party templates of arbitrary type. But, given a wrapper or C++11 alias you can turn CONTAINER into a template template parameter.

Note that none of the standard library container templates take a single template parameter, they have defaults that you generally do not use and so you usually only provide one, but none of the proposed answers so far will work for standard library templates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM