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() にデータを渡す別の方法はありますか?