0

以下のプログラムを書きました

#include <iostream>
template<typename C, typename Res, typename... Args>
class bind_class_t {
private:
  Res (C::*f)(Args...);
  C *c;
public:
  bind_class_t(Res (C::*f)(Args...), C* c) : f(f), c(c) { }
  Res operator() (Args... args) {
    return (c->*f)(args...);
  }
};

template<typename C, typename Res, typename... Args>
bind_class_t<C, Res, Args...>
bind_class(Res (C::*f)(Args...), C* c) {
  return bind_class<C, Res, Args...>(f, c);
}

class test {
public:
  int add(int x, int y) {
    return x + y;
  }
};

int main() {
  test t;
  // bind_class_t<test, int, int, int> b(&test::add, &t);
  bind_class_t<test, int, int, int> b = bind_class(&test::add, &t);
  std::cout << b(1, 2) << std::endl;
  return 0;
}

gcc 4.3.3 でコンパイルしたところ、セグメンテーション違反が発生しました。gdb とこのプログラムでしばらく過ごした後、関数とクラスのアドレスが混同されており、クラスのデータ アドレスの呼び出しが許可されていないように思えます。さらに、代わりにコメント行を使用すると、すべて正常に動作します。

他の誰かがこの動作を再現したり、ここで何が問題なのかを説明したりできますか?

4

1 に答える 1

5

あなたはおそらく必要です

return bind_class_t<C, Res, Args...>(f, c);

それ以外の

return bind_class<C, Res, Args...>(f, c);

そうしないと、無限の再帰が発生します。

于 2010-04-23T14:15:09.347 に答える