简体   繁体   English

相当于Java泛型的C ++

[英]C++ Equivalent of Java Generics

I need to convert some java classes into C++. 我需要将一些Java类转换为C ++。 For example, for a java interface that looks like this: 例如,对于如下所示的Java接口:

public interface ListenerManager<L> {

    void addListener(L listener);

    void removeListener(L listener);

}

My C++ is a bit rusty so I'm trying to figure out what the best way to translate this is. 我的C ++有点生疏,所以我想弄清楚什么是最好的翻译方法。 I was thinking something like this: 我在想这样的事情:

class IListener;
class ListenerManager
{
    virtual void add_listener(IListener listener);
    virtual void remove_listener(IListener listener);
};

and then define IListener as a base class somewhere else in the project. 然后将IListener定义为项目中其他地方的基类。

Is this the right way to go? 这是正确的方法吗?

EDIT: 编辑:

Thanks for the comments! 感谢您的评论! If I were to use templates, like this: 如果我要使用模板,如下所示:

template<class L>
class ListenerManager
{
    virtual void add_listener(L listener);
    virtual void remove_listener(L listener);
};

... but I had a number of different listener types, say, ListenerA and ListenerB , do I then need to make a specialization for each type in the implementation? ...但是我有许多不同的侦听器类型,例如ListenerAListenerB ,那么我是否需要对实现中的每种类型进行专门化设置?

You mean templates ? 你是说模板

Like eg 像例如

template<typename L>
class ListenerManager
{
    virtual void add_listener(L listener);
    virtual void remove_listener(L listener);
};

While they are not exactly the same, Java Generics can be translated as C++ Templates. 尽管它们并不完全相同,但是Java泛型可以转换为C ++模板。

template <typename T>
class ListenerManager
{
    virtual void add_listener(T listener);
    virtual void remove_listener(T listener);
};

You are after templates in C++; 您正在使用C ++中的模板 often compared, but not the same. 经常比较,但不一样。

template <class L>
class ListenerManager
{
public:
  void add_listener(L listener);
  void remove_listener(L listener);
};

This will create a class typed on L that is your listener manager. 这将创建一个基于L的类,它是您的侦听器管理器。 The following code with create a class, where each add_listener method is a template and a different type can be used. 以下代码创建一个类,其中每个add_listener方法都是一个模板,可以使用不同的类型。

class ListenerManager
{
  template <class L>
  void add_listener(L listener);
  // ...
};

Based on the question and the examples; 根据问题和示例; I suspect you are probably looking for a base class IListener of some sort to polymorphically handle the listeners in a container of some sort (in that way templates may not be the answer to the problem you have). 我怀疑您可能正在寻找某种基类IListener来多态处理某种容器中的侦听器(这样,模板可能无法解决您遇到的问题)。

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

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