开发者

Binder and variadic template ends up in a segmentation fault

开发者 https://www.devze.com 2022-12-28 11:07 出处:网络
I wrote the following program #include <iostream> template<typename C, typename Res, typename... Args>

I wrote the following program

#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.开发者_StackOverflow社区..), 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;
}

compiled it with gcc 4.3.3 and got a segmentation fault. After spending some time with gdb and this program it seems to me that the addresses of the function and the class are mixed up and a call of the data address of the class isn't allowed. Moreover if I use the commented line instead everything works fine.

Can anyone else reproduce this behavior and/or explain me what's going wrong here?


You need perhaps

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

instead of

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

Otherwise you'll get endless recursion.

0

精彩评论

暂无评论...
验证码 换一张
取 消