C++使用 STL 容器和 typedef 的模板类
我有一个如下所示的类:
#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 {
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);
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 {
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不要使用模板模板参数(在代码中继续),它们很脆弱且不灵活。如果需要,请使用重新绑定机制(std::allocator 是一个示例),但在这种情况下不需要:
与 std::queue 和 std::stack 进行比较,它们也遵循此模式。
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:
Compare to std::queue and std::stack, which also follow this pattern.
您应该能够在 typename 之后直接使用“container”,如示例中所示。当编译器运行时,它的类型规范将被扩展。
尝试编译一下...
You should be able to use 'container' directly after typename as you have it in your example. It's type specification will be expanded when the compiler runs.
Try compiling it...
我认为如果您使用类型特征可能会更容易。 STL和boost中的每个容器都有typedef的编号,其中value_type(请参考http:// www.cplusplus.com/reference/stl/vector/)。
所以你的代码可能看起来像:
I think it might be easier if you use type traits. Every container in STL and boost has number off typedef, among them value_type (consult reference http://www.cplusplus.com/reference/stl/vector/).
So your code may look like: