代码之家  ›  专栏  ›  技术社区  ›  mre

使用STL容器和TyPulf的C++模板类

  •  2
  • mre  · 技术社区  · 15 年前

    我有一个班级像这样:

    #include <vector>
    #include "record.h"
    #include "sortcalls.h"
    
    template<
        typename T,
        template<typename , typename Allocator = std::allocator<T> > class Cont = std::vector>
    class Sort: public SortCall {
    

    这段代码正在运行,我在其他类中这样称呼它:

    Comparator c; // comparison functor
    Sort< Record, std::vector > s(c);
    

    现在我想能够将容器切换到另一个容器,比如说列表。 所以我认为typedef应该是整洁的。应该是这样的

    typedef std::vector<Record> container;  // Default record container
    
    template<
        typename T,
        template< typename, typename container > // ???
    class Sort: public SortCall {
    
    3 回复  |  直到 15 年前
        1
  •  5
  •   Roger Pate    15 年前

    不使用模板模板参数( 继续 在您的代码中),它们是脆弱和不灵活的。如果需要,请使用重新绑定机制(例如std::allocator),但在这种情况下不使用:

    template<class T, class Cont=std::vector<T> >
    struct Sort {
      typedef Cont container_type; // if you need to access it from outside the class
      // similar to std::vector::value_type (which you might want to add here too)
    };
    
    typedef Sort<int, std::list<int> > IntListSort;
    

    与std::queue和std::stack比较,后者也遵循此模式。

        2
  •  0
  •   Jordan Parmer    15 年前

    您应该能够在typename后面直接使用“container”,就像在示例中那样。它的类型规范将在编译器运行时扩展。

    尝试编译它…

        3
  •  0
  •   Anycorn    15 年前

    我认为如果你使用类型特征可能会更容易。stl和boost中的每个容器都有number off typedef,其中value_type(请参考 http://www.cplusplus.com/reference/stl/vector/ ) 因此,您的代码可能如下所示:

    template<class C>
    class sort {
      typedef typename C::value_type value_type; // equivalent to T in your case.
      // similarly you can get allocator, iterator, etc.