How to forward declare an alias without knowing the actual implementation?

  alias, c++, forward-declaration, using

I’m using a Bridge pattern where the interface forward-declares an Impl class without knowing it’s definition. The class definition uses just a pointer to this implementation, so no definition is needed here:

// interface.h

class Interface1 {
public:
    void method();
private:
    class Impl;
    Impl *impl;
};

class Interface2 {
public:
    void method();
private:
    class Impl;
    Impl *impl;
};

The client code uses these interfaces without knowing the implementations as well:

// client.cpp

#include <interface.h>

void useInterface1() {
    Interface1 obj;
    obj.method();
}

The actual bridge from each interface to its implementation is defined in a cpp file:

// bridge.cpp

#include <interface.h>
#include <implementation.h>

void Interface1::method() {
    impl->method();
}

void Interface2::method() {
    impl->method();
}

Now I can define the implementations:

// implementation.h

#include <interface.h>

class Interface1::Impl {
public:
    void method() {}
};

class Interface2::Impl {
public:
    void method() {}
};

As you can see, the implementations are two distinct classes, but they are similar. What I want to do is to define a single class Implementation and make InterfaceX::Impl aliases of this class. Something like this (this is just a pseudocode that doesn’t compile):

class Interface1 {
    // Use the name `Impl` here without knowing what stands behind this name:
    using Impl;
    Impl *impl;
};

class Implementation {
    // ...
};

// Define the InterfaceX::Impl classes either as separate classes or as aliases:
using Interface1::Impl = Implementation;
using Interface2::Impl = Implementation;

How can I do that? Please note that the implementation cannot be a template parameter of the interface because in this case the implementation shall be known to the client code.

Source: Windows Questions C++

LEAVE A COMMENT