我有一个类,看起来像这样:
#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/