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

使用STL容器和Type的C++模板类,c++,stl,vector,typedef,typename,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 { 这段代

我有一门课看起来像这样:

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

您应该能够在typename之后直接使用“container”,就像您在示例中使用的那样。它的类型规范将在编译器运行时展开


试着编译它…

我想如果你使用类型特征可能会更容易。STL和boost中的每个容器都有数字off typedef,其中包括value_type consult reference。 因此,您的代码可能如下所示:

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.

不要在代码中使用模板参数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进行比较。

我不确定我是否理解;你没有在任何地方使用排序。此外,Alloc是为编译器保留的;你应该把它改成分配器之类的。我不知道为什么模板参数会这么复杂。为什么不模板类排序。。。使用Sort s?实际上,您应该只删除_Alloc和默认值,这两个值都不是必需的,提供它们也没有任何帮助。我甚至不确定默认值是合法的C++。@ RoGePATE-AlOC甚至用我自己的容器编译和运行。但我很高兴知道这不是一种好的风格:@UncleBens是的,这确实有效!我说的对吗,我不会失去任何灵活性来对除记录之外的其他内容进行排序?在模板参数上使用这种设计是我们很多人通过艰苦的方式学会的事情之一,很多人都会眯着眼睛看标准,挠头+1.这可能是未来发展的最佳解决方案。我投你一票。尽管UncleBens提供了第一个有效的解决方案。谢谢大家!