[英]C++ Callback function, calling member variable inside static function
我最近決定開始使用回調函數,以使我的生活更輕松。 但是,我有一個問題:
#include <iostream>
#include <functional>
#include <memory>
class setCallback
{
public:
setCallback() {}
setCallback(std::function<int()> func) : callback(func) { }
int call() { return callback(); }
private:
std::function<int()> callback;
};
class callThis
{
public:
callThis() : number(10) {}
static int another()
{
return number;
}
int number;
};
int main(int argc, char** argv[])
{
std::shared_ptr<setCallback> caller;
std::shared_ptr<callThis> funcholder;
funcholder.reset(new callThis);
caller.reset(new setCallback(funcholder->another));
std::cout << caller->call() << "\n";
std::cin.get();
}
從代碼中可以看到,我將函數從“ callthis”插入“ setCallBack”。 這使我可以保留該功能,以備以后使用。 但是,如果我嘗試將“ callthis”中的成員變量加載到靜態函數中,這顯然是行不通的(使用值可以)。
有沒有解決的辦法? 我想使用靜態函數訪問在類中找到的變量; (可選)避免在傳入回調時使用靜態函數(但由於回調的工作方式,我認為這是不可能的)。
我聽說過包裝器類,但是我不確定如何實現它。 一些見識將不勝感激。
非常感謝。
編輯:
用B Sahu解決了帶有回調函數的調用變量
使用回調解決了調用函數,而無需使該函數被靜態調用並保持合理的解耦
我研究了如何使用C ++ 11調用非靜態函數。 我認為,如果有人最終遇到與我相同的問題,這可能會很有用。 這與R Sahu提出的原理相同,但是,使用其中找到的類型和過程最終會更干凈。 使用std :: bind(class :: func,object)可以有效地獲得相同的結果。
int main(int argc, char** argv)
{
std::function<void(void)> somefunc;
Functionholder func;
somefunc = std::bind(&Functionholder::say, &func);
}
這歸功於: 這個美麗的人
在更復雜的示例中使用時,該類具有一個包含要調用的函數的類,一個將使用該函數並在需要時調用它的調用者類以及一個綁定器/狀態類(請注意,我將其用於游戲UI) ,您實際上可以得到一些合理整齊且未耦合的代碼:
#include <iostream>
#include <functional>
class Functionholder
{
public:
void say() { std::cout << "hello!\n"; }
};
class CallbackHandler
{
public:
CallbackHandler(){}
CallbackHandler(std::function<void()> call) { callback = call; }
void update()
{
//something happens to call this
callback();
}
std::function<void()> callback;
};
class TheState
{
public:
TheState()
{
hand = CallbackHandler(std::bind(&Functionholder::say, &func));
}
void update() { hand.update(); }
Functionholder func;
CallbackHandler hand;
};
int main(int argc, char** argv)
{
TheState state;
state.update();
std::function<void(void)> somefunc;
std::cin.get();
}
如果您有任何改進,請告訴我!
提供使用用戶指定的數據調用回調函數的功能。 然后,使用回調函數中的數據。
#include <iostream>
#include <functional>
#include <memory>
class setCallback
{
public:
setCallback() {}
setCallback(std::function<int(void*)> func) : callback(func) { }
int call(void* data) { return callback(data); }
private:
std::function<int(void*)> callback;
};
class callThis
{
public:
callThis() : number(10) {}
static int another(void* data)
{
callThis* ptr = static_cast<callThis*>(data);
return ptr->number;
}
int number;
};
// Fixed this line. You had
// int main(int argc, char** argv[])
int main(int argc, char** argv)
{
std::shared_ptr<setCallback> caller;
std::shared_ptr<callThis> funcholder;
funcholder.reset(new callThis);
caller.reset(new setCallback(callThis::another));
std::cout << caller->call(funcholder.get()) << "\n";
std::cin.get();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.