我正在尝试编写一个宏,以便更容易地在C ++中使用回调。我的所有回调都是成员函数,将this
作为第一个参数,第二个参数的类型继承自公共基类。
通常的方法是:
register_callback(boost::bind(&my_class::member_function, this, _1));
我很想写:
register_callback(HANDLER(member_function));
请注意,它将始终在同一个类中使用。
即使typeof
被认为是一种不好的做法,但对于缺少__class__
宏来获取当前的类名,这听起来是一个很好的解决方案。
以下代码有效:
typedef typeof(*this) CLASS;
boost::bind(& CLASS :: member_function, this, _1)(my_argument);
但我无法在宏中使用此代码,该宏将作为register_callback
的参数提供。
我试过了:
#define HANDLER(FUN) \
boost::bind(& typeof(*this) :: member_function, this, _1);
由于我不理解的原因不起作用。引用GCC文档:
typeof
- 构造可以在任何可以使用typedef名称的地方使用。
我的编译器是GCC 4.4,即使我更喜欢标准的东西,也接受GCC特定的解决方案。
答案 0 :(得分:1)
您的问题可能是产量my_class&
的类型。它似乎适用于boost::remove_reference
:
#include <boost/bind.hpp>
#include <boost/type_traits.hpp>
#include <iostream>
struct X
{
void foo(int i) { std::cout << i << '\n'; }
void bar() {boost::bind(&boost::remove_reference<typeof(*this)>::type::foo, this, _1)(10); }
};
int main()
{
X x;
x.bar();
}
使用BOOST_TYPEOF
和使用C ++ 0x decltype