求解答C++ Functor相关的问题!

ranqingfa 2015-11-10 03:23:23
下面是一个头文件的内容,貌似全是Functor相关的东西,希望大神给以解答或者指明应该看哪方面的资料,目前只了解貌似都是仿函数相关的知识,只是没有找到能很好解释的文章,望大神们推荐比较好的文章,谢谢!

#pragma once
#ifndef __FUNCTOR_H__
#define __FUNCTOR_H__

#define FUNCTOR_TYPEDEF(name, rettype, ...) \
typedef Functor<rettype, ## __VA_ARGS__> name

#define FUNCTOR_DECLARE(name, rettype, ...) \
Functor<rettype, ## __VA_ARGS__> name

#define FUNCTOR_BIND(obj, func, rettype, ...) \
Functor<rettype, ## __VA_ARGS__>::bind<remove_reference<decltype(*obj)>::type, func>(obj)

#define FUNCTOR_BIND_MEMBER(func, rettype, ...) \
Functor<rettype, ## __VA_ARGS__>::bind<remove_reference<decltype(*this)>::type, func>(this)

template <class RetType, class... Args>
class Functor
{
public:
constexpr Functor(void *obj, RetType (*method)(void *obj, Args...))
: _obj(obj)
, _method(method)
{
}

// Allow to construct an empty Functor
constexpr Functor(decltype(nullptr))
: Functor(nullptr, nullptr) { }

constexpr Functor()
: Functor(nullptr, nullptr) { }

// Call the method on the obj this Functor is bound to
RetType operator()(Args... args) const
{
return _method(_obj, args...);
}

// Compare if the two Functors are calling the same method in the same
// object
inline bool operator==(const Functor<RetType, Args...>& rhs)
{
return _obj == rhs._obj && _method == rhs._method;
}

// Allow to check if there's a method set in the Functor
explicit operator bool() const
{
return _method != nullptr;
}

template<class T, RetType (T::*method)(Args...)>
static constexpr Functor bind(T *obj)
{
return { obj, method_wrapper<T, method> };
}

private:
void *_obj;
RetType (*_method)(void *obj, Args...);

template<class T, RetType (T::*method)(Args...)>
static RetType method_wrapper(void *obj, Args... args)
{
T *t = static_cast<T*>(obj);
return (t->*method)(args...);
}
};

template< class T > struct remove_reference {typedef T type;};
template< class T > struct remove_reference<T&> {typedef T type;};
template< class T > struct remove_reference<T&&> {typedef T type;};

#endif
...全文
182 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
引用 2 楼 ranqingfa 的回复:
[quote=引用 1 楼 akirya 的回复:] 用了不少C++11的东西,变长模板参数 、 constexpr 感觉这个Functor不如直接用 bind
好吧,对我这个C++新手来说,确实不容易啊,看来编写程序的人C++很牛啊,是国外的! 大神,能稍微解释解释吗?[/quote] 就是把 成员函数和某个对象绑定,转换成一个函数对象。这样调用的时候就不需要传递对象来调用成员函数了。
yshuise 2015-11-10
  • 打赏
  • 举报
回复
全部展开,慢慢理解消化。 想当初,我阅读了很多的BOOST源码,可惜现在有好几年了,都忘记了。 反正,就是要把宏展开来理解。
ranqingfa 2015-11-10
  • 打赏
  • 举报
回复
引用 1 楼 akirya 的回复:
用了不少C++11的东西,变长模板参数 、 constexpr 感觉这个Functor不如直接用 bind
好吧,对我这个C++新手来说,确实不容易啊,看来编写程序的人C++很牛啊,是国外的! 大神,能稍微解释解释吗?
  • 打赏
  • 举报
回复
用了不少C++11的东西,变长模板参数 、 constexpr 感觉这个Functor不如直接用 bind

64,642

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧