【问题标题】:Partial template template specialization部分模板模板专业化
【发布时间】:2012-05-10 05:02:13
【问题描述】:

有这个代码:

template<typename T, template<typename, typename> class OuterCont, template<typename, typename> class InnerCont, class Alloc=std::allocator<T>>
class ContProxy { 
    OuterCont<T, InnerCont<T, Alloc>> _container;
};
typedef ContProxy<int, std::vector, std::list> IntCont;

但在某些情况下需要使用T* 而不是std::list&lt;T&gt; 作为InnerCont - 像这样:

template<typename T, template<typename, typename> class OuterCont, T*, class Alloc=std::allocator<T>>
class ContProxy { 
    OuterCont<T, T*> _container;
};

在这种情况下是否可以使用“模板模板”参数的部分特化?
或者如何以最小的头痛存档它..

【问题讨论】:

    标签: c++ templates partial-specialization template-templates


    【解决方案1】:

    简单地在 type 上进行模板制作通常更容易。您无法使用模板模板真正捕捉所有情况——如果有人想使用具有六个模板参数的容器怎么办?所以尝试这样的事情:

    template <typename T, typename C>
    struct ContProxy
    {
        typedef C                    container_type;
        typedef typename C::second_type second_type;
    
        container_type container_;
    };
    
    ContProxy<int, MyContainer<int, std::list<int>> p;
    

    【讨论】:

      【解决方案2】:

      我也会采用 kerrek 的解决方案,但除此之外,我能想到的最好的办法就是这个。

      问题在于 InnerCont 在基本模板中被声明为模板类型,因此您不能再将其专门用于原始指针。所以你可以创建一个代表指针的虚拟模板并使用它。

      template<typename,typename> class PtrInnerCont; //just a dummy template that does nothing
      
      template<typename T, template<typename, typename> class OuterCont, template<typename, typename> class InnerCont, class Alloc=std::allocator<T>>
      class ContProxy  { 
          OuterCont<T, PtrInnerCont<T, Alloc>> _container;
      };
      typedef ContProxy<int, std::vector, std::list> IntCont;
      
      template<typename T, template<typename, typename> class OuterCont, class Alloc>
      class ContProxy<T, OuterCont, PtrInnerCont, Alloc> { 
          OuterCont<T, T*> _container;
      };
      
      typedef ContProxy<int, std::vector, PtrInnerCont> MyCont;
      

      【讨论】:

        【解决方案3】:

        你不能真正做你已经在做的事情。不是以标准方式。 C++ 容器不采用相同的模板参数。

        做这样的事情:

        template< typename T, 
                  template<typename, typename> class OuterCont,
                  template<typename, typename> class InnerCont, 
                  class Alloc=std::allocator<T>>
        class ContProxy { 
            typename OuterCont<T, typename InnerCont<T, Alloc>::type>::type _container;
        };
        

        然后你可以像这样创建不同的容器生成器:

        template < typename T, typename A = std::allocator<T> >
        struct vector_gen { typedef std::vector<T,A> type; };
        

        或者你的指针:

        template < typename T, typename Ignored >
        struct pointer_gen { typedef T* type; };
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-04-12
          • 2015-08-21
          相关资源
          最近更新 更多