栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

类似于Python的C ++装饰器

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

类似于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.3Calling the decorated function.a = 10

ps

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

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/652121.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号