ATK
ATK

Reputation: 1526

A generic interface in c++

I am trying to design a broker interface which has a well defined set of APIs - however, the arguments are not well defined. For example,

class broker{
    virtual void add(Type type)=0; // Type is to illustrate that undecided arguemnt
    virtual remove(Type type)=0;
}

My problem is that the argument of the virtual functions depend on the actual implementation. Each implementation would configure a specific configuration class Type.

Ideally:

class ConfigABroker : public broker {
    void add(ConfigA configA) { .... }
    void remove(ConfigA configA) { .... }
}

Where the type ConfigA is a simple C++ class with member variables

I am looking for a c++ design pattern which can overcome this issue. I tried looking into type erasure however it seems I am end up in the same problem again.

Upvotes: 1

Views: 318

Answers (1)

paolo
paolo

Reputation: 2400

You can have class broker depend on a template parameter:

template <typename Type>
class broker {
   public:
    virtual void add(Type type) = 0;
    virtual void remove(Type type) = 0;
};

class ConfigA { /* ... */ };

class ConfigABroker : public broker<ConfigA> {
   public:
    void add(ConfigA configA) override { /* ... */ }
    void remove(ConfigA configA) override { /* ... */ }
};

Upvotes: 3

Related Questions