【问题标题】:Specializing a Functor for logging专门用于记录的 Functor
【发布时间】:2012-07-31 04:13:56
【问题描述】:

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

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

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
        }
    }
}

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

这可能吗?

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

【问题讨论】:

    标签: c++ functor


    【解决方案1】:

    使用可变参数模板:

    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
      }
    }
    

    【讨论】:

    • 另外,这里有一个很好的介绍:cplusplus.com/articles/EhvU7k9E
    • 废话,我应该提到我在编译器标志方面受到限制。我不能使用 C++0x。
    • @MarkP:如果没有 C++0x,恐怕你所要求的实际上是不可能的。我已经编辑了我的答案,以便为您提供一个可能的解决方案,但它不是最佳的。
    • 我有一种感觉,这只能在 C++0x 中实现。还是谢谢。
    • 大多数 C++ 编译器都有一个可以执行 C99 风格的预处理器 __VA_ARGS__ - 这意味着您可以通过 #define runFunc(...) if(p-&gt;t(time(NULL), __VA_ARGS__)) { /* ... */ } 实现它。同样,标准不是强制(除非 C++0x/11),但比可变参数模板更多的编译器支持。
    猜你喜欢
    • 2015-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-20
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多