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

标签 c++ stl vector typedef 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 {

这段代码正在工作,我从其他类中这样调用它:

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 {

最佳答案

不要使用模板模板参数(在代码中继续),它们很脆弱且不灵活。如果需要,请使用重新绑定(bind)机制(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 相比,它们也遵循此模式。

关于使用 STL 容器和 typedef 的 C++ 模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2240620/

相关文章:

c++ - 在 C++ 中重写非虚函数时出错

c++ - 使用 boost::pool_allocator 和 boost::unordered_map 的语法是什么?

c++11 - std::thread::id 跨进程是否唯一?

c++ - 通过mexfunction从C++将int类型的N个 vector 返回到matlab?

c++ - 由于 C++ 中的段错误而导致应用程序崩溃的方法

c++ - 双链表删除带索引的节点 C++

c++ - 模板特化的成员函数类型

std::vector<Test> 与 std::vector<Test*> 的性能

c++ - 为什么我不能在c++中 `+1`的迭代器中使用 `map`?

c++ - 标准在定义可见性方面对unordered_set的Value类型有什么要求