在被定义为(指针)函数类型的变量上获得必须的(指针)函数类型
我正在为函数创建一个typedef,该函数将用于调用存储在字符串到函数指针映射。我相信这个问题与如何通过我的代码中的许多对象声明和引用类型有关,但这是我能想到如何做我需要的唯一方法在被定义为(指针)函数类型的变量上获得必须的(指针)函数类型
这是fmap.h在这里,我声明FMAP类和executefunctions班,为的typedef函数指针是对公众成员的FMAP
class Web;
class Matlab;
class Word;
class Node;
class ExecFunctions
{
public:
ExecFunctions(){}
/**
Function: travel
*/
int travel(Web *concepts, Matlab *mat, Word * words, int reqIdx, string theWord, vector<string> *dependsMet);
};
class FMap
{
public:
typedef int (ExecFunctions::*ExecFunc)(Web *, Matlab *, Word *, int, string, vector<string> *);
ExecFunc getFunc(string funcName){
return theFuncMap.descrToFuncMap[funcName];
}
private:
class FuncMap {
public:
FuncMap() {
descrToFuncMap["travel"] = &ExecFunctions::travel;
}
std::map<std::string, ExecFunc> descrToFuncMap;
};
};
#endif
旁边的第一行是web.h我只包括什么,我认为是相关部件
#include "fmap.h"
class Node
{
private:
....
//pointer to execcution function
FMap::ExecFunc func;
//fmap function used to access execution function pointers
FMap *functionMap;
.....
public:
FMap::ExecFunc getExecFunc();
};
现在我认为是t他相信web.cpp的一部分
Node::Node(string name, Node *nodeParent)
{
attrList = new Attr();
nodeName = name;
........
func = functionMap->getFunc(name);
}
现在终于。这是我得到错误的地方。在错误行解释我得到的错误之前,有三行注释。
void process(Util myUtil, Web *concepts, Matlab *mat, string path)
{
int funcP
bool dependsProcessed = false;
vector<string> *dependsDone = new vector<string>();
FMap::ExecFunc funcToCall;
funcToCall = realMeanings[i][j]->getConcept()->getExecFunc();
//the line bellow this comment is where I'm getting the error. Visual Studio says
//that funcToCall must have (pointer-to) function type, and then the VS compiler says
//diabot.cpp(177): error C2064: term does not evaluate to a function taking 6 arguments
funcPtrRet = funcToCall(concepts, mat, realMeanings[i][j], reqConceptsIdx[i][j], queryWords[i], dependsDone);
return;
}
任何人都可以给任何帮助将不胜感激。
谢谢大家提前
我不知道我没有迷失在阅读整个代码,但我相信你一定叫上ExecFunctions
实例funcToCall()
,因为ExecFunc
是一个方法指针类型。
是什么给,如果你使用的语法如下:
ExecFunctions ef;
ef.*funcToCall(...);
或
ExecFunctions* ef = ...;
ef->*funcToCall(...);
第一个根本不会改变错误,它仍然给出一个必须有(指针)函数类型错误,第二个给出了无法分配类型FMap :: ExecFunc来键入ExecFunctions而ExecFunctions没有成员funcToCall – jeffminton 2011-04-28 07:56:11
你funcToCall
不过是你在呼唤像一个简单的函数指针的指针到成员函数,您需要在ExecFunctions
类的实例上调用它,否则请考虑将ExecFunctions
更改为命名空间并将ExecFunc
更改为int()(Web *, Matlab *, Word *, int, string, vector<string> *);
问题是成员函数和自由函数在C++中是不同的,如果你想到它,有一个很好的理由(隐含的隐含的this
参数)。有您要取决于你真正需要做的不同的解决方案:
低电平:
- 制作的功能非成员(将它们移到命名空间的水平)。
- 使函数静态(去除隐藏的
this
,然后该类型定义将起作用。首先考虑第一个选项,C++不会强制您在类中添加所有代码,有时函数不属于类。创建一个无意义的类仅仅是为了存储一些自由函数是没有意义的 - 更改typedef以反映它们是成员:
typedef return_type (type::*member_function)(arg_type);
- 但这需要创建一个要调用成员函数的type
对象。
高级别:
- 使用
std::function
(C++ 0x中)或bind
boost::function
一起:这是最灵活的,因为它可以让你bind
不仅是免费的功能,和静态函数而且通过提供实际的对象来提供成员函数。但是:如果您不需要灵活性,则可以使用其他选项之一。
这就是很多代码,其中大部分代码可能与问题无关。你可以尝试简化你的例子吗? – 2011-04-28 07:26:13
对不起,我无法将代码分解为基本问题。我把它削减了一下。让我知道如果它仍然很多 – jeffminton 2011-04-28 07:35:27