简体   繁体   English

同时管理指针向量和对象向量的模板类

[英]template class that manages both a vector of pointers and a vector of objects

I have two template class that are very similar: one manages a vector of T* objects and does things to these pointers, another manages a vector of T objects and does the same thing to these objects. 我有两个非常相似的模板类:一个管理一个T *对象的向量并对这些指针执行操作,另一个管理一个T对象的向量对这些对象执行相同操作。

Is there some way I can have a single class that manages either a list of pointers or a list of objects? 有什么办法可以让一个类管理一个指针列表或一个对象列表?

Yes. 是。 Interact with the members of your vector via a helper functor that turns T& into T* in the value case. 通过辅助函子与vector的成员进行交互,该辅助函子在有价情况下将T&变成T* Any other behavior differences can be similarly factored into traits/helper types and handled similarly. 可以将其他任何行为差异类似地分解为特征/帮手类型,并进行类似处理。

Take the functor as an additional template parameter to your template . 以仿函数作为一个额外的template参数您的template Possibly hide it by having two public template s that pass the appropriate helper functor to the implementation template . 可能通过具有两个公共template将其隐藏,这些公共template将适当的辅助函数传递给实现template

In extremely simple cases, you could do away with the functor, and just use overloading on pointers vs references. 在非常简单的情况下,您可以取消函子,而只对指针和引用使用重载。

Yes. 是。 Use a template specialization : 使用模板专业化

First, declare the class as you would normally: 首先,像往常一样声明类:

template <typename T>
class Foo
{
     ...
};

Then declare a specialization for pointer types: 然后为指针类型声明一个特殊化:

template <typename T>
class Foo<T*>
{
    //re-define any methods you want to be different for the pointer implementation.
};

The class can then be used normally, but if the template parameter is a pointer type, it will use the T* implementation: 然后可以正常使用该类,但是如果template参数是指针类型,它将使用T*实现:

Foo<Bar> fooBar; //uses the default implementation
Foo<Bar*> fooPbar; //uses the specialized implementation

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM