Pat Mustard
Pat Mustard

Reputation: 1902

C++ Equivalent of Java Generics

I need to convert some java classes into C++. For example, for a java interface that looks like this:

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. 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.

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?

Upvotes: 1

Views: 303

Answers (3)

Niall
Niall

Reputation: 30604

You are after templates in 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. The following code with create a class, where each add_listener method is a template and a different type can be used.

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).

Upvotes: 0

vz0
vz0

Reputation: 32923

While they are not exactly the same, Java Generics can be translated as C++ Templates.

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

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409364

You mean templates?

Like e.g.

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

Upvotes: 4

Related Questions