繁体   English   中英

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

[英]C++ Template class using STL container and a typedef

我有一堂课,看起来像这样:

#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 {

不要使用模板模板参数(代码中的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;

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

在示例中,您应该能够直接在typename之后使用“ container”。 当编译器运行时,它的类型规范将得到扩展。

尝试编译...

我认为使用类型特征可能会更容易。 STL和boost中的每个容器都有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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM