私の C++ アプリケーションには、(i) メイン スレッド、(ii) バックグラウンド スレッドの 2 つのスレッドがあります。次のように定義されたクラスがあります。
class helper
{
public:
bool login(const string& username, const string& password);
void logout();
private:
bool loginInternal(const string& username, const string& password);
void logoutInternal();
}
helper::login() および helper::logout() 関数 (および、さまざまな戻り値の型と、params および param 型の数を持つ他のいくつかのメンバー関数) がメイン スレッドで呼び出されます。これらの関数の実装では、対応する内部関数がキューに入れられ、バックグラウンド スレッドがこれらの内部関数をキューに入れられた順序で呼び出します。だから、このようなもの:
bool helper::login(const string& username, const string& password)
{
queue.push_back(boost::bind(&helper::loginInternal, this, username, password));
}
void helper::logout()
{
queue.push_back(boost::bind(&helper::logoutInternal, this));
}
この間ずっとバックグラウンド スレッドが実行され、キューがいっぱいになるのを待っています。いっぱいになるとすぐに、このバックグラウンド スレッドはキュー内の関数の呼び出しを開始します。
queue.front()();
queue.pop_front();
問題は、そのようなキューをどのように定義するかです。
deque<???> queue;
同じキューに異なる署名を持つコールバック関数を保持できるように、このキューのデータ型は何でしょうか?
編集: これが解決策です (J. Calleja に感謝):
typedef boost::function<void ()> Command;
deque<Command> queue;
そして、次のようにファンクターを呼び出します。
// Execute the command at the front
Command cmd = queue.front();
cmd();
// remove the executed command from the queue
queue.pop_front();