mbed で Callback 関数を扱う

mbed のコアAPI、 Ticker などでも使われている、FunctionPointer を使う。

typedef FunctionPointerArg1<void, void> FunctionPointer;
typedef FunctionPointerArg1<void, int> event_callback_t;

の定義の通り、引数なしなら FunctionPointer を、int を引数に渡したいなら event_callback_t を使う。FunctionPointerArg1 を使って自分で定義するのももちろん良い。ちなみに FunctionPointerArg2 は無い。

FunctionPointer を使うと、いわゆる bind 的なことも

void attach(T *object, R (T::*member)(void)) { // bind
void attach(R (*function)(void)) {

でしてくれるのでちょっと便利。


そもそも C++11 の <std::function> 等々が使えれば良いんじゃ無い、と思うけど、mbed OS では

We are not using C++11 yet so do not write code compliant to this standard.

というポリシーなので、このような事が必要。