如何将方法作为参数传递
How to pass a method as parameter?
拥有这个类:
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
方法,但没有成功。
你怎么称呼它?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&)) ;
您尝试做的通常被称为闭包,这是函数式编程中的一个重要概念。与其重新发明轮子,我建议你看看Boost::Phoenix,它提供了一个不错的同行评审库。
http://www.boost.org/doc/libs/1_47_0/libs/phoenix/doc/html/index.html然而,由于c++是一种静态类型语言,您将不得不做一些封送处理。c++中没有类似泛型函数(对象)的东西
相关文章:
- 将成员函数指针作为参数传递给模板方法
- 在 C++ 中将非指定类型作为参数传递的最佳方法?
- 如何将成员函数作为参数传递并在派生对象上执行方法列表
- 如何将带有参数的方法传递给线程以执行?
- 在C++中传递数组作为函数参数的方法
- 将带有模板化方法的类作为带有GCC的模板参数传递
- 将派生类作为参数传递给方法,该方法是具有智能指针的基类
- 将私有数据成员作为默认参数传递给该类的公共方法时出错
- 如何将提升回调作为参数传递给方法?
- 将方法作为模板化参数传递 C++11
- 将 std::ofstream 对象作为参数传递给类方法
- 将给定的 vararg 参数传递给另一个函数的适当方法是什么?
- 将指针类方法作为参数传递给其他类方法C
- 如何将基类方法超载作为参数传递到C 中的模板类
- 将非静态数据成员作为默认参数传递给方法
- 将数组作为函数参数传递,并在其上调用开始/结束方法
- 将对象数组作为参数传递的最佳方法是什么
- 将参数传递给模板函数的方法
- 基本C - 构造contaning对象引用,并将其作为方法参数传递
- C++ "Best"参数传递方法