【问题标题】:C++ template class inheriting from a template class从模板类继承的 C++ 模板类
【发布时间】:2012-05-18 18:28:08
【问题描述】:

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

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

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

gcc 一直在说 “ 之前的预期 unqualified-id

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

我尝试做模板

【问题讨论】:

    标签: c++ templates


    【解决方案1】:

    让用户指定容器的常用方法是将实际容器 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&lt;int, CrazyContainer&lt;int, true, Blue&gt;&gt; x;,您无需担心容器的详细信息。

    【讨论】:

      【解决方案2】:

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

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

      但是,这不适用于任何标准容器,因为它们具有额外的模板参数(如分配器)。

      请注意,typename 必须在 SmallContainer&lt; T &gt;::type 之前,否则编译器将假定它引用了一个值。

      【讨论】:

      • 可变参数模板签名将匹配任何具体签名:template &lt;typename...&gt; class Container.
      • @Kerrek SB:除非它有非类型模板参数,比如std::array
      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-10-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-07
        • 2018-01-18
        相关资源
        最近更新 更多