【问题标题】:How I can declare a pointer to different classes that share common interfaces?如何声明指向共享公共接口的不同类的指针?
【发布时间】:2017-04-24 18:04:01
【问题描述】:

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

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

它们不只共享一个公共基类。是否可以声明一个既可以引用 A 类又可以引用 B 类的指针类型?

请注意,我使用的是第 3 方库,无法重新定义 A 和 B。如果可以,我会这样做:

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

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

Base *pBase;

【问题讨论】:

  • 通用基类是either Interface1 or Interface2。如果你不能重构代码,真的没有办法绕过它。您应该使用哪一种取决于具体情况和您当前的需求。
  • 我不建议使用它,但void* 可以引用任何内容。也可以创建一个“指针”类,它可以根据它们的类型同时保存。

标签: c++ class interface


【解决方案1】:

如果你不能重构代码,你就不能直接这样做。

也就是说,您仍然可以创建一个擦除类型的类,并且可以在需要指向 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 和所有其他类型的指针。
无论如何,我不知道真正的问题是什么,我无法从问题中弄清楚。
因此,我希望它有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-06
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多