[英]callback in C++ struct
我一直在嘗試用c ++實現回調函數。 在一個類中,我有一個struct,許多方法,以及一個方法,該方法使用其他方法之一作為其參數來創建struct的實例。
該結構有許多其他變量,但這里描述了一個例子:
class MYCLASS
{
public:
MYCLASS();
struct TEST{
std::function<int(int)> foo;
};
int plus(int x){
return x + 1;
}
int minus(int x){
return x - 1;
}
void sim(){
TEST T; // make an instance of TEST
T.foo = plus(5); // assign TEST.foo a function (plus or minus)
T.foo(); // call the method we assigned
}
};
在sim
方法中,我想創建一個test
實例,並根據一些標准給它plus
或minus
。 我試圖給實例T
plus
函數並隨后調用它的兩行都是不正確的。
如果你想延遲對T.foo
的調用,那么你可以使用這樣的lambda:
T.foo = [this](int x) { return plus(x); };
T.foo(5);
如果成員函數plus()
和minus()
足夠簡單,就像你已經顯示的那樣,你可以將它們作為struct TEST
lambda函數。 由於無捕獲的lambda可以存儲在類型化的函數指針中 ,因此以下內容可以執行您想要的操作。 查看現場演示
#include <iostream>
class MYCLASS
{
int m_var = 5; // just for demonstration
public:
MYCLASS() = default;
struct TEST
{
using fPtrType = int(*)(int); // function pointer type
const fPtrType foo1 = [](int x) { return x + 1; }; // plus function
const fPtrType foo2 = [](int x) { return x - 1; }; // minus function
};
void sim()
{
TEST T;
std::cout << "Answer from int PLUS(int): " << T.foo1(m_var) << std::endl;
std::cout << "Answer from int MINUS(int): " << T.foo2(m_var) << std::endl;
}
};
如果上面的代碼在代碼中有很大的改變,請再次對成員函數使用類型化的函數指針,並執行以下操作; 這將避免不必要的復制 (通過捕獲)類實例到lambda和模板實例化和其他性能問題同時伴隨着std::function
。
#include <iostream>
class MYCLASS
{
using fPtrType = int(MYCLASS::*)(int); // class member function pointer type
public:
MYCLASS() = default;
struct TEST { fPtrType foo = nullptr; };
int plus(int x) { return x + 1; }
int minus(int x) { return x - 1; }
void sim()
{
TEST T;
T.foo = &MYCLASS::plus; // now you can
std::cout << "Answer from int PLUS(int): " << (this->*T.MYCLASS::TEST::foo)(5) << std::endl;
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ syntax would be a bit ugly
// later same ptr variable for minus()
T.foo = &MYCLASS::minus;
int answer = (this->*T.MYCLASS::TEST::foo)(5);
std::cout << "Answer from int MINUS(int): " << answer << std::endl;
}
};
int main()
{
MYCLASS obj;
obj.sim();
return 0;
}
輸出:
Answer from int PLUS(int): 6
Answer from int MINUS(int): 4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.