[英]Pointer to a member-function
我想執行以下操作:我有兩個類,A和B,並希望將A的功能綁定到B的功能,以便每當有人在B中調用該功能時,就會調用A的功能。
因此,基本上,這是場景:( 重要的 A和B應該是獨立的類)
這將是A類:
class A {
private:
// some needed variables for "doStuff"
public:
void doStuff(int param1, float *param2);
}
這是B班
class B {
private:
void callTheFunction();
public:
void setTheFunction();
}
這就是我要使用這些類的方式:
B *b = new B();
A *a = new A();
b->setTheFunction(a->doStuff); // obviously not working :(
我讀過,這可以通過std :: function實現,這將如何工作? 另外,每當callTheFunction()
時,這是否會對性能產生影響? 在我的示例中,它是一個音頻回調函數,該函數應調用另一個類的樣本生成函數。
這是一個基本骨架:
struct B
{
A * a_instance;
void (A::*a_method)(int, float *);
B() : a_instance(nullptr), a_method(nullptr) {}
void callTheFunction(int a, float * b)
{
if (a_instance && a_method)
{
(a_instance->*a_method)(a, b);
}
}
};
用法:
A a;
B b;
b.a_instance = &a;
b.a_method = &A::doStuff;
b.callTheFunction(10, nullptr);
基於用法的解決方案C ++ 11 std :: function和std :: bind。
#include <functional>
#include <stdlib.h>
#include <iostream>
using functionType = std::function <void (int, float *)>;
class A
{
public:
void doStuff (int param1, float * param2)
{
std::cout << param1 << " " << (param2 ? * param2 : 0.0f) << std::endl;
};
};
class B
{
public:
void callTheFunction ()
{
function (i, f);
};
void setTheFunction (const functionType specificFunction)
{
function = specificFunction;
};
functionType function {};
int i {0};
float * f {nullptr};
};
int main (int argc, char * argv [])
{
using std::placeholders::_1;
using std::placeholders::_2;
A a;
B b;
b.setTheFunction (std::bind (& A::doStuff, & a, _1, _2) );
b.callTheFunction ();
b.i = 42;
b.f = new float {7.0f};
b.callTheFunction ();
delete b.f;
return EXIT_SUCCESS;
}
編譯:
$ g ++ func.cpp -std = c ++ 11 -o func
輸出:
$ ./func
0 0
42 7
這是我的基本解決方案
class A {
private:
// some needed variables for "doStuff"
public:
void doStuff(int param1, float *param2)
{
}
};
typedef void (A::*TMethodPtr)(int param1, float *param2);
class B {
private:
TMethodPtr m_pMethod;
A* m_Obj;
void callTheFunction()
{
float f;
(m_Obj->*m_pMethod)(10, &f);
}
public:
void setTheFunction(A* Obj, TMethodPtr pMethod)
{
m_pMethod = pMethod;
m_Obj = Obj;
}
};
void main()
{
B *b = new B();
A *a = new A();
b->setTheFunction(a, A::doStuff); // now work :)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.