【问题标题】:Can a member function pointer refer to a method of one of several different classes?成员函数指针可以引用几个不同类之一的方法吗?
【发布时间】:2021-12-19 00:29:40
【问题描述】:

这就是我所拥有的:

class Foo;
class Bar;
class FooBar 
{
public:
        FooBar( Foo &f, void ( Foo::* signal )( FooBar* ) ) 
                : m_Foo(&f)
                , fp_Foo(signal) {};
        FooBar( Bar &b, void ( Bar::* signal )( FooBar* ) ) 
                : m_Bar(&b)
                , fp_Bar(signal) {};

protected:
        void ( Foo::*fp_Foo )( FooBar* );
        void ( Bar::*fp_Bar )( FooBar* );

private: 
        Foo *m_Foo{nullptr};
        Bar *m_Bar{nullptr};
};

这就是我想要的:

class Foo;
class Bar;
class FooBar 
{
public:
        FooBar( Foo &f, void ( Foo::* signal )( FooBar* ) ) 
                : m_Foo(&f)
                , fp(signal) {};
        FooBar( Bar &b, void ( Bar::* signal )( FooBar* ) ) 
                : m_Bar(&b)
                , fp(signal) {};

protected:
        void ( <???>::*fp )( FooBar* ); // Deduplicated

private: 
        Foo *m_Foo{nullptr};
        Bar *m_Bar{nullptr};
};

我只想要一组成员函数指针,它们可以同时代表FooBar

不使用模板可以吗?

谢谢。

【问题讨论】:

  • QList 不是 QObject。子类 QObject 并用列表组成子类。
  • 我认为从这个问题中删除 Qt 将有助于使其更加清晰。您是在询问使用派生类获取的成员数据指针是否与从基类获取的指针相同?
  • @FrançoisAndrieux,OP 有一个 XY 问题。 Qt 就在标签中。并且已经给出了解决方案。
  • @FrançoisAndrieux 是的,这是真的。我将编辑问题并取出 Qt cruft,因为它已经浪费了某人的时间。 Are you asking if a member data pointer taken using a derived class the same as that pointer taken from the base class?没有。
  • @Anon 我认为成员函数指针不可能做到这一点。该类是其类型的一部分,它们不可相互转换。你可以试试std::function&lt;void(FooBar*)&gt;。否则,您可以尝试使用模板。

标签: c++ casting c++17 function-pointers member-function-pointers


【解决方案1】:

在我看来,你有一个 XY 问题。这就是为什么我将专注于您真正想要实现的目标,即:

我想向基于 QList 的类添加一些信号,用于插入、更改和删除。然而,Q_OBJECT 宏不适用于此:

class CardList : public QList&lt;Card*&gt;

原因

QList 不是QObject

解决方案

子类QObject 并用列表组成子类。

示例

这是我为您编写的一个简单示例,用于演示建议的解决方案:

#include <QObject>

class Card;

class CardList : public QObject // inheritance
{
    Q_OBJECT
public:
    explicit CardList(QObject *parent = nullptr);

    void addCard(Card *); // emit cardAdded here
    int cardCount() const;
    Card *card(int pos);
    bool removeCard(int pos); // emit cardRemoved here

private:
    QList<Card *> m_cards; // composition

signals:
    void cardAdded(int pos);
    void cardRemoved(int pos);
};

现在你可以拥有:

class Game : public QObject
{
    ...
private:
    CardList *m_cards;
    ...
}

class Player : public QObject
{
    ...
private:
    CardList *m_cards;
    ...
}

话虽如此,也许模型会更好地满足您的应用程序的需求。

【讨论】:

  • 我不想重新定义QList的所有功能。我的问题非常具体,是否可以转换成员函数指针。 That is why I will concentrate on what you actually want to achieve, i.e.: 绝不是我真正想要实现的目标,因为我宁愿只拥有两组成员函数指针,也不愿做你提议的事情。
  • @Anon 这是你的软件,伙计。如果你想玩得开心,那就继续吧。我也许可以给你指路,但我不能(也不想)强迫你走。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多