我的班级看起来像这样:
#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 {
答案 0 :(得分: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;
比较std :: queue和std :: stack,它们也遵循这种模式。
答案 1 :(得分:0)
您应该可以在typename后直接使用'container',就像在示例中一样。当编译器运行时,它的类型规范将被扩展。
尝试编译它......
答案 2 :(得分:0)
我认为如果使用类型特征可能会更容易。 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.