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.
精彩评论