クラスのインスタンスとメンバ関数を引数に持つコールバック関数
#include <stdio.h> class myclass { public: myclass() { value = 5; } void foo() { printf("myclass::foo i = %d\n", value); } int value; }; void callback(myclass *p, void (myclass::*function)()) { (p->*function)(); } int main() { puts("main"); myclass c; callback(&c, &myclass::foo); }
C++のメンバ関数をメモリに保存し、呼び出す方法
クラスを使用せずにC言語のみであれば、下記コードのように関数のポインタを保存し呼び出すことが可能です。
=====test1.cpp=====
#include
void (*func)() = 0;
void foo() {
puts("foo");
}
int main() {
puts("main");
func = foo;
func();
}
===================
=====出力結果=====
>gcc test1.cpp -o test1.exe
>test1.exe
main
foo
==================
一方で、C++のメンバ関数のポインタで同様のことを行おうとするとエラーが発生してしまいます。
=====test2.cpp=====
#include
void (*func)() = 0;
class myclass
{
public:
myclass();
void foo();
int value;
};
myclass::myclass() {
value = 5;
}
void myclass::foo() {
printf("myclass::foo i = %d\n", value);
}
int main() {
puts("main");
myclass c;
func = c.foo;
func();
}
===================
=====出力結果=====
>gcc test2.cpp -o test2.exe
test2.cpp: In function 'int main()':
test2.cpp:23:12: error: argument of type 'void (myclass::)()' does not match 'void (*)()'
==================