我如何声明指向共享公共接口的不同类的指针?

时间:2016-12-09 09:43:59

标签: c++ class interface

我正在使用一些像这样定义的第三方库类。

class A : public Interface1, public Interface2 {};
class B : public Interface1, public Interface2 {};

他们不共享一个共同的基类。是否可以声明一个可以引用A类和B类的单指针类型?

请注意我使用第三方库并且无法重新定义A和B.如果可以,我会这样做:

class Base : public Interface1, public Interface2 {};
class A : public Base {};
class B : public Base {};

然后我可以简单地使用指向Base类的指针。

Base *pBase;

1 个答案:

答案 0 :(得分:0)

如果您无法重构代码,则无法直接执行此操作。

也就是说,您仍然可以创建一个擦除类型的类,只要需要指向Interface1Interface2的指针,就可以使用该类。 举个例子:

struct S {
    template<typename T>
    S(T *t): iface1{t}, iface2{t} {}

    operator Interface1 *() { return iface1; }
    operator Interface2 *() { return iface2; }

private:
    Interface1 *iface1;
    Interface2 *iface2;
};

它有一个主要缺点,我不知道你是否可以处理:指向S的指针无法分配给指向InterfaceN的指针。
换句话说:

struct Interface1 {};
struct Interface2 {};

class A : public Interface1, public Interface2 {};
class B : public Interface1, public Interface2 {};

struct S {
    template<typename T>
    S(T *t): iface1{t}, iface2{t} {}

    operator Interface1 *() { return iface1; }
    operator Interface2 *() { return iface2; }

private:
    Interface1 *iface1;
    Interface2 *iface2;
};

int main() {
    A a;
    S sa{&a};

    // S can be assigned to a pointer to InterfaceN
    Interface1 *i1ptr = sa;
    Interface2 *i2ptr = sa;

    S *sptr = &sa;

    // sptr cannot be assigned to a pointer
    // to InterfaceN but you can get one
    // out of it dereferencing
    i1ptr = *sptr;
    i2ptr = *sptr;
}

如果你能接受,这是一个肮脏而可行的解决方法。

说实话,我不明白你为什么要那样做。您可以简单地创建函数模板并传递指向AB和所有其他类型的指针。
无论如何,我不知道什么是真正的问题,我无法从这个问题中找出答案 因此,我希望它有所帮助。