私はいくつかのパラメータを最初にバインドすることによっていくつかのロジックを抽象化しながらコールバックを提供するためにstd :: bindを使用しています。すなわちCでのstd :: bindのエミュレート
void start() {
int secret_id = 43534;
//Bind the secret_id to the callback function object
std::function<void(std::string)> cb = std::bind(&callback, secret_id, std::placeholders::_1);
do_action(cb);
}
void do_action(std::function<void(std::string)> cb) {
std::string result = "hello world";
//Do some things...
//Call the callback
cb(result);
}
void callback(int secret_id, std::string result) {
//Callback can now do something with the result and secret_id
}
したがって、上記の例では、do_actionはsecret_idについて知る必要はありませんし、他の機能は、独自のsecret_idを持たずに、それを再利用することができます。これは、do_actionが何らかの非同期操作である場合に特に便利です。
私の質問は、Cのみを使用して関数ポインタにパラメータ値をバインドする方法はありますか?
std :: bindをエミュレートしないと、ニュートラルdo_action()を複雑にすることなく、first()からcallback()にデータを渡す別の方法がありますか?
"C"でこれを実現する方法は確かです。 LibFFIはクロージャを提供し、ほとんどの主要OSに移植可能です:http://sourceware.org/libffi/ –
@BojanNikolic良い点、libffiはトランポリンよりもはるかに一般的です。 libffiを使用してOPの問題を解決するnaという例の答えが評価されるかもしれません。 – user4815162342