1

重複の可能性:
メンバー関数の関数ポインター

C++で以下のようなことを考え出す必要があります。

次のクラスにメンバー関数があります。

class myClass {
public:
       void myFunc();

};

オブジェクトの myFunc() であるコールバック関数を呼び出して渡す必要がある別のライブラリに次の関数があります

void AnotherFunction((void*)(pCallback)())
{
   // Here I will call back function
}

上記を達成するにはどうすればよいですか?コールバックを渡すクラスの静的関数を認識していますが、ここでは関数がスレッドセーフであることを確認する必要があります。static を使用せずに、どうすればこの要件を達成できますか?

4

2 に答える 2

4

現在、「最善の」解決策は、例外を吐き出すことです。

void f(void(*fp)()) { fp(); }
void mah_func() { 
    try { 
        throw; 
    } catch(my_class* m) {
        m->func();
    }
}
int main() {
    my_class m;
    try {
        throw &m;
    } catch(my_class* p) {
        f(mah_func);
    }
}

これは嫌な悪用ですが、スレッドセーフで最も移植性があります。

于 2012-10-01T10:39:30.417 に答える
-1

内部的には、メンバー関数は常に this-pointer を「非表示」の最初の引数として持つため、関数にはシグネチャ void(myClass *) が付けられます。AnotherFunction の署名を に変更できる場合void AnotherFunction(std::function<void()> callback)は、次のことができます。

#include <functional>
#include <iostream>

void AnotherFunction(std::function<void()> callback)
{
  callback();
}

void fun()
{
  std::cout << "fun()" << std::endl;
}

class Foo
{
public:
  Foo(int i) : i_(i) { }

  static void gun()
  {
    std::cout << "Foo::gun()" << std::endl;
  }

  void hun()
  {
    std::cout << "Foo(" << i_ << ")::hun()" << std::endl;
  }

protected:
private:
  int i_;
};

int main()
{
  Foo foo(666);
  AnotherFunction(fun);
  AnotherFunction(Foo::gun);
  AnotherFunction(std::bind(&Foo::hun, foo));
}

これは次を印刷します:

fun()
Foo::gun()
Foo(666)::hun()
于 2012-10-01T10:53:11.110 に答える