【问题标题】:How to pass a method as parameter?如何将方法作为参数传递?
【发布时间】:2011-10-14 17:06:04
【问题描述】:

有这门课:

class Automat
{
private:
    // some members ... 
public:
    Automat();
    ~Automat();
    void addQ(string& newQ) ; 
    void addCharacter(char& newChar)  ;
    void addLamda(Lamda& newLamda) ; 
    void setStartSituation(string& startQ) ; 
    void addAccQ(string& newQ) ;
    bool checkWord(string& wordToCheck) ; 
    friend istream& operator >> (istream &isInput, Automat &newAutomat);
    string& getSituation(string& startSituation) ; 
};

还有一个名为Menu 的类,它具有以下方法:

void Menu::handleStringSituations(string &stringOfSituation , Automat* autoToHandle ,void (Automat::*methodToDo) () )
{
    // some code ...
      (*autoToHandle).*methodToDo() ; 
}

(*autoToHandle).*methodToDo() ; 行出现错误。

如您所见,我试图将 Automat 类中的任何方法作为参数传递给 handleStringSituations 方法,但没有成功。

【问题讨论】:

  • 我可能会建议重新设计。如果您描述了您的目标(而不是您实现目标的尝试),我们可以看看。有些人可能会建议std::function,但我认为你可能没有以正确的方式解决这个问题。

标签: c++ methods


【解决方案1】:

您尝试执行的操作通常称为闭包,这是函数式编程中的一个重要概念。我建议您不要重新发明轮子,而是研究 Boost::Phoenix,它在一个很好的、经过同行评审的库中提供了这一点。

http://www.boost.org/doc/libs/1_47_0/libs/phoenix/doc/html/index.html

但是,由于 C++ 是一种静态类型语言,因此您必须进行一些编组。 C++ 中没有泛型函数(对象)之类的东西。

【讨论】:

    【解决方案2】:

    你会怎么称呼它? C++ 不是动态类型语言;它是静态类型的。因此,您调用的所有内容都必须具有一组特定的参数,并且必须键入每个参数。没有办法调用带有一定数量参数的“某些函数”,希望可以在运行时进行整理。

    您需要一个特定的界面。 methodToDo 需要有某种接口;没有一个,你不能调用它。

    您能做的最好的事情是拥有多个版本的handleStringSituations,每个版本采用不同的成员指针类型:

    void handleStringSituations(string &stringOfSituation , Automat* autoToHandle ,void (Automat::*methodToDo) ()) ;
    void handleStringSituations(string &stringOfSituation , Automat* autoToHandle ,void (Automat::*methodToDo) (string&)) ;
    void handleStringSituations(string &stringOfSituation , Automat* autoToHandle ,void (Automat::*methodToDo) (Lamda&)) ;
    

    【讨论】:

    • 不能传递void*,然后可以将其转换为任何所需的签名吗?毕竟,对函数的引用只是一个指针。
    • @aroth:成员指针与常规指针不同。并且将函数指针转换为void* 无论如何都是未定义的行为(认为它通常有效)。将成员指针转换为 void* 几乎永远不会起作用,因为成员指针的大小或类型很少与常规指针相同。
    • @Nicol Bolas:怎么会这样?你能举一些例子吗?
    • @vines:查看codeproject.com/KB/cpp/FastDelegate.aspx 进行深入分析。这篇文章来自 2004 年,但基本问题保持不变。
    猜你喜欢
    • 2015-03-10
    • 2015-01-22
    • 2019-06-12
    • 1970-01-01
    • 1970-01-01
    • 2010-11-16
    • 2020-07-03
    相关资源
    最近更新 更多