从模板类继承的C ++模板类

时间:2012-05-18 18:28:09

标签: c++ templates

我尝试从另一个模板类继承一个部分专用的模板类。我不知道该怎么做。这是我的代码:

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

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

和gcc一直说     在'&lt;'标记之前的预期模板名称     期望'{'在'&lt;'标记之前     在'&lt;'标记

之前预期的非限定标识

我的对象的想法是让AnotherClass成为我想要的任何其他类型的向量的通用容器。

我试图做模板&lt;模板CONTAINER,typename T&gt;等...没有任何成功。 任何的想法 ? 感谢...

3 个答案:

答案 0 :(得分:3)

让用户指定容器的常用方法是将实际容器 class 作为模板参数,而不仅仅是容器模板。这也是标准库如何指定容器适配器的方式。例如:

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;
};

现在,用户可以创建其他实例,例如Foo<int, CrazyContainer<int, true, Blue>> x;,您无需担心其容器的详细信息。

答案 1 :(得分:2)

这适用于只有一个模板参数的容器:

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

然而,这对任何标准容器都不起作用,因为它们有额外的模板参数(如分配器)。

请注意typename之前需要SmallContainer< T >::type,否则编译器会认为它引用了一个值。

答案 2 :(得分:0)

这无法真正完成,无论如何都不能使用STL容器。您可以为每个容器创建一个类似SmallContainer的包装器,以便您可以提供默认参数,但STL容器在大多数情况下不共享公共参数。此外,没有办法匹配任意类型的第三方模板。但是,给定一个包装器或C ++ 11别名,您可以将CONTAINER转换为模板模板参数。

请注意,没有一个标准库容器模板采用单个模板参数,它们具有您通常不使用的默认值,因此通常只提供一个,但到目前为止,所提出的答案都不适用于标准库模板。