【发布时间】:2011-02-03 07:24:05
【问题描述】:
下面我有一个将类成员函数绑定到全局函数的概念。这样做的主要目的是使用 C++ 实现 C 风格的回调函数。能否以更好的方式完成(例如,不使用 final 宏或typeof,或使用 C++0x 功能)?
#include <iostream>
using namespace std;
template<typename MF> struct mf_wrapper_helper;
template<typename R, typename T>
struct mf_wrapper_helper<R (T::*)()>
{
template <R (T::*F)()>
static R wrapper(T *foo) { return (foo->*F)(); }
};
template<typename R, typename T, typename T1>
struct mf_wrapper_helper<R (T::*)(T1)>
{
template <R (T::*F)(T1)>
static R wrapper(T *foo, T1 arg1) { return (foo->*F)(arg1); }
};
#define BIND_MF(mf) \
mf_wrapper_helper<typeof(mf)>::wrapper<mf>
struct Foo
{
void x() { cout << "Foo::x()" << endl; }
void x1(int i) { cout << "Foo::x1(" << i << ")" << endl; }
};
int
main()
{
typedef void (*f_t)(Foo *);
typedef void (*f1_t)(Foo *, int i);
Foo foo;
f_t f_p = BIND_MF(&Foo::x);
(*f_p)(&foo);
f1_t f1_p = BIND_MF(&Foo::x1);
(*f1_p)(&foo, 314);
return 0;
}
【问题讨论】:
-
你用的是什么编译器?如果您可以使用 C++0x,只需使用无捕获的 lambda,它们就可以转换为函数指针。还有,为什么要动态分配
main的东西? -
忽略
new- 与问题无关。我使用 GCC 4.5 和 ICC 11.1。不确定 lambda 在这里有什么帮助,因为Lambda functions are function objects of an implementation-dependent type。其实我对C++0x不太了解,代码示例不胜感激。 -
投票结束,因为这个问题可能更适合codereview.stackexchange.com
-
@klimkin:就像我说的,你可以制作一个就地 lambda,它可以转换为函数指针。我们只需要知道 C++0x 是否是一个选项。 “忽略那个新的 - 对这个问题无关紧要。”没错,为什么会在那里? :) @John:我不知道,也许如果它是一个官方交换网站,但现在它应该放在这里。 (忽略我认为代码审查网站是不必要的。)
-
有一点值得一提,虽然不是真正的答案:C++0x 关键字
decltype与 g++ 编译器扩展typeof基本相同。