提高回调注册可读性的宏
我正在尝试编写一个宏,以便更轻松地使用 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 特定的解决方案也是可以接受的。
I'm trying to write a macro to make a specific usage of callbacks in C++ easier. All my callbacks are member functions and will take this
as first argument and a second one whose type inherits from a common base class.
The usual way to go is:
register_callback(boost::bind(&my_class::member_function, this, _1));
I'd love to write:
register_callback(HANDLER(member_function));
Note that it will always be used within the same class.
Even if typeof
is considered as a bad practice, it sounds like a pretty solution to the lack of __class__
macro to get the current class name.
The following code works:
typedef typeof(*this) CLASS;
boost::bind(& CLASS :: member_function, this, _1)(my_argument);
but I can't use this code in a macro which will be given as argument to register_callback
.
I've tried:
#define HANDLER(FUN) \
boost::bind(& typeof(*this) :: member_function, this, _1);
which doesn't work for reasons I don't understand. Quoting GCC documentation:
A
typeof
-construct can be used anywhere a typedef name could be used.
My compiler is GCC 4.4, and even if I'd prefer something standard, GCC-specific solutions are accepted.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的问题可能是 typeof 产生
my_class&
。它似乎可以与boost::remove_reference
一起使用:使用
BOOST_TYPEOF
可能更便携,并且在 C++0xdecltype
中Your problem might be that typeof yields
my_class&
. It appears to work withboost::remove_reference
:It might be more portable to use
BOOST_TYPEOF
, and in C++0xdecltype