idanshmu
idanshmu

Reputation: 5271

Call functions polymorphically outside of polymorphic objects

Say I have a bunch of storage classes X1,X2,,,Xn.
Say I have Writer class that provides write() functions for each one of the storage classes:

class Writer
{
public:
  void write(const X1& x);
  ...
  void write(const Xn& x);
};

Now I have to add more storage classes as follows:

class B;
class D1: public B;
class D2: public B;

to be initialize as follows:

B* d1 = new D1();
B* d2 = new D2();

Now I need to enhance class Writer to include the following functions:

void write(const B* b);
void write(const D1* d);
void write(const D2* d);

But this will not work as I intend. Calling write(d1) does not invoke void write(const D1* d). I'm losing the ability to call write() polymorphically.

seems to me like this is a job for visitor pattern (correct me if I'm wrong. I'm not that experience in this pattern and might got it wrong).

Regardless of whether visitor pattern is the way to go or not, are their any other suggestions for resolving this?

Notes

  1. Writer is a complex class that write storage classes to binary files. None of the storage classes needs to be aware of the way they are serialized to a file. Storage is separated from the writing process.
  2. dynamic_cast is an oblivious solution but I'd like to avoid that. it is not clean and besides, what if I have a lot of derived classes.

Upvotes: 0

Views: 204

Answers (1)

Simple
Simple

Reputation: 14420

You should be able to get around this with double dispatch:

class Writer
{
public:
    void write(const B* x)
    {
        x->on_write(*this);
    }

    void accept(const D1* x);
    void accept(const D2* x);
};

class B
{
public:
    virtual void on_write(Writer& x) = 0;
};

class D1 : public B
{
public:
    void on_write(Writer& x) override { x.accept(this); }
};

class D2 : public B
{
public:
    void on_write(Writer& x) override { x.accept(this); }
};

Upvotes: 2

Related Questions