C ++ Template类使用STL容器和typedef [英] C++ Template class using STL container and a typedef

查看:322
本文介绍了C ++ Template类使用STL容器和typedef的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类看起来像这样:

I have a class looking like this:

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

这段代码正常工作,这来自其他类:

This code is working and I'm calling it like this from other classes:

Comparator c; // comparison functor
Sort< Record, std::vector > s(c);

现在我想能够将容器切换到另一个容器,比如列表。
所以我认为typedef会整齐。它应该是

Now I want to be able to switch the containers to another container, say a list. So I thought a typedef would be neat. It should be something like

typedef std::vector<Record> container;  // Default record container

template<
    typename T,
    template< typename, typename container > // ???
class Sort: public SortCall {


推荐答案

Don在代码中使用模板模板参数( Cont ),它们脆弱且不灵活。如果需要,使用重新绑定机制(std :: allocator是一个示例),但是在这种情况下不需要:

Don't use template template parameters (Cont in your code), they are brittle and inflexible. Use a rebind mechanism if you need to (std::allocator is an example), but you don't in this case:

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进行比较,它们也遵循此模式。

Compare to std::queue and std::stack, which also follow this pattern.

这篇关于C ++ Template类使用STL容器和typedef的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆