是否可以重新綁定std :: function以指向相同的函數,但使用不同的對象實例?將std :: function綁定到不同對象實例的相同函數
說如果我有一個對象具有綁定到另一個函數的std :: function,但是如果該對象被複制到另一個實例,我想重新將std :: function重新綁定到該新實例的舊例。
#include "stdafx.h"
#include <iostream>
#include <functional>
class EventHandler
{
public:
int Num;
std::function<int()> OnEvent;
EventHandler (int inNum)
{
Num = inNum;
}
EventHandler (const EventHandler& other)
{
Num = other.Num;
OnEvent = other.OnEvent; //TODO: Need some way to redirect the std::function to the new instance rather than having the delegate point to the original object's handler.
}
int HandleEvent()
{
return Num;
}
};
int main()
{
EventHandler a(4);
a.OnEvent = std::bind(&EventHandler::HandleEvent, a);
EventHandler b(a);
b.Num = 5;
//Uncommenting the line below is a manual way of redirecting event handler to the new instance.
//b.OnEvent = std::bind(&EventHandler::HandleEvent, b);
int aResult = a.OnEvent();
int bResult = b.OnEvent();
//This will print out 4 and 4 instead of 4 and 5 since b is still bound to a's event handler.
std::cout << "aResult=" << aResult << " bResult=" << bResult << '\n';
return 0;
}
我打算有一個std ::函數的包裝來存儲附加信息。
是問題怎麼做這個事情具體,或者是如何讓這個概念在代碼中工作?我的意思是,還有其他方法可以正確獲取EventHandler設置。例如,構造函數可以只是std :: bind(&EventHandler :: HandleEvent,this);.還有其他選擇,但我不清楚你的目標。 – tmruss
更多關於如何讓這個概念在代碼中工作。我想我可能爲了清晰起見而簡化了這個例子。我正在使用的實際代碼庫與對象具有父子關係。當父母被複制時,其子女也被複制。我需要遷移孩子的std ::函數來指向新的實例,而不是指向原件。 –
讓我先說這個,說我可能會嘗試找到一種不同的方式來組織事情,然後用我將要說的來解決這個問題。這聽起來像是一個設計問題,可能有一個更簡單的解決方案。然而,你可以創建一個模板包裝器,存儲一個指向成員的指針,該指針將被綁定到函數中。然後,在您的賦值運算符中,您使用指向成員的指針作爲目標,將「this」作爲實例進行綁定。 做到這一點的唯一原因是,如果你試圖使它通用。如果它總是相同的功能,我會重新綁定它。 – tmruss