专门用于日志记录的Functor

Specializing a Functor for logging

本文关键字:Functor 记录 日志 用于      更新时间:2023-10-16

我一直潜伏在这里,试图弄清楚Functor是否能做我需要它做的事情。

我想做的是包装对类方法的调用,并以某种方式捕获函数返回的值。考虑到我的Functor类,我需要做什么才能将我的评论转化为代码:

template < typename Func >
class MySpecializedFunctor
{
    Func t;
    MyObject& p;
public:
    MyFunctor( MyObject &obj, Func f )
    {
        p = obj;
        t = f;
    }
    void runFunc( ... )
    {
        // Can I use an ellipsis '...' to pass values into t->xxxx() ???
        // Assume the first param is always time, the others are never the same
        bool b = p->t( time( NULL ), /* first value of ... */, /* second value of ... */ );
        if ( !b )
        {
            // log error here
        }
    }
}

因为这是一个函数,所以被包装的函数可能有n个参数。

这可能吗?

编辑:我不能使用C++0X。

使用可变模板:

template <typename... Args>
void runFunc(Args&&... args)
{
  bool b = p->t(time(NULL), std::forward<Args>(args)...);
  if ( !b )
  {
    // log error here
  }
}

或者重载runFunc,如果您的编译器不支持可变模板或完美转发:

// this one support 3 const arguments, you will need to overload
// all variations of arguments count and constness
template <typename Arg1, typename Arg2, typename Arg3>
void runFunc(const Arg1& arg1, const Arg2& arg2, const Arg3& arg3)
{
  bool b = p->t(time(NULL), arg1, arg2, arg3);
  if ( !b )
  {
    // log error here
  }
}