简体   繁体   English

如何将函数指针传递给重载成员函数作为参数

[英]How to pass a function pointer to overloaded member function as parameter

This is related to code generation. 这与代码生成有关。

I have a class A which is generated from model, in which I have two overloads of function f like below: 我有一个从模型生成的类A ,其中有两个函数f重载,如下所示:

class A
{
  public:
    void f(int a){}
    void f(int a, int b){}
}

I then have a separate part of the system which is not generated from model, but written in hand crafted C++. 然后,我有一个系统的单独部分,它不是由模型生成的,而是由手工C ++编写的。 Here I would like to access the function f on an object. 在这里,我想访问对象上的函数f From the model I can pass data to the hand crafted part of the system, but not the other way around, since the generated file is not available for compilation when I build my hand crafted code. 从模型中,我可以将数据传递到系统的手工部分,但不能反过来,因为生成我的手工代码时,生成的文件不可用于编译。

My idea is to pass a function pointer from the model to where I need it. 我的想法是将函数指针从模型传递到需要的地方。 This, as I have understood it so far, includes static_cast to solve the overload issue and then I can pass a pointer to the function as a parameter to some other hand crafted function. 到目前为止,据我所知,它包括static_cast以解决重载问题,然后我可以将指向该函数的指针作为参数传递给其他一些手工函数。

The function used to pass the pointer to the hand crafted part of the system is declared like this (here A is not known): 用于将指针传递到系统的手工部分的函数是这样声明的(此处A未知):

void passPointer(int, void (*f)(int, int));

My cast and function call looks like: 我的演员和函数调用看起来像:

handCraftedObject->passPointer(17, static_cast<void (A::*)(int, int)> (&A::f) );

My compilation error is: 我的编译错误是:

:   no known conversion for argument 2 from 'void (A::*)(int, int)' to 'void (*)(int, int)

I hope this doesn't mean i have to know the class A where the function passing the function pointer is declared. 我希望这并不意味着我必须知道声明了传递函数指针的函数的类A This is not possible in my system. 在我的系统中这是不可能的。

Member function pointer has different type than function pointer and cannot be converted to it. 成员函数指针的类型与函数指针的类型不同,无法将其转换为成员指针。 The simplest way is to use boost/std(C++11) bind and function . 最简单的方法是使用boost / std(C ++ 11) bindfunction

void passPointer(int, const std::function<void(int, int)>&);

than just 不只是

handCraftedObject->passPointer
(
   17, std::bind(static_cast<void (A::*)(int, int)> (&A::f), std::ref(a_instance), 
   std::placeholders::_1, std::placeholders::_2)
);

Also you cannot use boost/C++11, you can make function f static , then all will works fine. 另外,您不能使用boost / C ++ 11,可以将函数f static ,然后一切正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM