使用STL容器和typedef的C++ Template类

mre*_*mre 2 c++ stl typedef vector typename

我有一个类看起来像这样:

#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 {
Run Code Online (Sandbox Code Playgroud)

这段代码正在运行,我从其他类中调用它:

Comparator c; // comparison functor
Sort< Record, std::vector > s(c);
Run Code Online (Sandbox Code Playgroud)

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

typedef std::vector<Record> container;  // Default record container

template<
    typename T,
    template< typename, typename container > // ???
class Sort: public SortCall {
Run Code Online (Sandbox Code Playgroud)

小智 5

不要使用模板模板参数(代码中的Cont),它们很脆弱且不灵活.如果需要,可以使用重新绑定机制(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;
Run Code Online (Sandbox Code Playgroud)

与std :: queue和std :: stack相比,它也遵循这种模式.