C ++函数修饰器 [英] C++ function decorator

查看:73
本文介绍了C ++函数修饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种装饰C ++中的函数或lambda的方法。目标是在函数调用之前和之后做一些事情。如我所见,最接近使用的东西是std :: function,但它必须具有其参数的类型。

I am looking for a way to decorate functions or lambdas in C++. The goal is to do something before and after the function call. As I've seen the closest thing to use is std::function but it needs to have the types of its arguments.

class FunctionDecorator
{
public:
    FunctionDecorator( std::function func )
        : m_func( func )

    void operator()()
    {
        // do some stuff prior to function call

        m_func();

        // do stuff after function call
    }

private:
    std::function m_func;
};

如果按模板类型可以在std :: function中使用并且可以推断出它,那就太好了当我以某种方式将指针传递给函数或std :: bind的结果时。
在C ++中是可能的。

It would be great if by template type could be used in std::function and it could deduce it somehow when i pass pointer to a function or a result from std::bind. Is such thing possible in C++.

推荐答案

只需使用完整模板,而无需std :: function:

Just go full template, without std::function:

template< typename Func >
class FunctionDecorator
{
public:
  FunctionDecorator( Func func )
    : m_func( std::move(func) )
  {}

  void operator()()
  {
    // do some stuff prior to function call
    m_func();
    // do stuff after function call
  }

private:
  Func m_func;
};

template< typename Func >
FunctionDecorator<Func> decorate(Func func) {
  return FunctionDecorator<Func>(std::move(func));
}

这篇关于C ++函数修饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆