宏来提高回调注册的可读性

时间:2010-03-13 11:45:24

标签: c++ callback this boost-bind typeof

我正在尝试编写一个宏,以便更容易地在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特定的解决方案。

1 个答案:

答案 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

可能更具可移植性
相关问题