您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

类似于Python的C ++装饰器

类似于Python的C ++装饰器

std::function 提供了我提出的解决方案的大多数构建块。

这是我建议的解决方案。

#include <iostream>
#include <functional>

//-------------------------------
// BEGIN decorator implementation
//-------------------------------

template <class> struct Decorator;

template <class R, class... Args>
struct Decorator<R(Args ...)>
{
   Decorator(std::function<R(Args ...)> f) : f_(f) {}

   R operator()(Args ... args)
   {
      std::cout << "Calling the decorated function.\n";
      return f_(args...);
   }
   std::function<R(Args ...)> f_;
};

template<class R, class... Args>
Decorator<R(Args...)> makeDecorator(R (*f)(Args ...))
{
   return Decorator<R(Args...)>(std::function<R(Args...)>(f));
}

//-------------------------------
// END decorator implementation
//-------------------------------

//-------------------------------
// Sample functions to decorate.
//-------------------------------

// Proposed solution doesn't work with default values.
// int decorated1(int a, float b = 0)
int decorated1(int a, float b)
{
   std::cout << "a = " << a << ", b = " << b << std::endl;
   return 0;
}

void decorated2(int a)
{
   std::cout << "a = " << a << std::endl;
}

int main()
{
   auto method1 = makeDecorator(decorated1);
   method1(10, 30.3);
   auto method2 = makeDecorator(decorated2);
   method2(10);
}

输出

Calling the decorated function.
a = 10, b = 30.3
Calling the decorated function.
a = 10

Decorator提供了一个可以进行功能调用以外的其他功能的地方。如果您想简单地传递至std::function,可以使用:

template<class R, class... Args >
std::function<R(Args...)> makeDecorator(R (*f)(Args ...))
{
   return std::function<R(Args...)>(f);
}
python 2022/1/1 18:52:58 有311人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶