如何传递一个方法作为参数? [英] How to pass a method as parameter?

查看:154
本文介绍了如何传递一个方法作为参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有这个类:

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 ); c>给出一个错误。

The line (*autoToHandle).*methodToDo() ; gives an error .

正如你可以看到我试图传递 Automat 类作为 handleStringSituations 方法的参数,没有成功。

As you can see I trying to pass any method from Automat class as a parameter to handleStringSituations method with no success.

推荐答案

你尝试做的是通常被称为闭包,一个强大的函数式编程概念。

What you try to do is usually known as closure, a concept strong in functional programming. Rather than reinventing the wheel, I suggest you look into Boost::Phoenix, which provides this in a nice, peer reviewed library.

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

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

However, since C++ is a statically typed language, you will have to do some marshalling. There is no such thing like a generic function (object) in C++.

这篇关于如何传递一个方法作为参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆