2

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

これは一種の Functor であるため、ラップされる関数は n 個のパラメーターを持つことができます。

これは可能ですか?

編集: C++0X を使用できません。

4

1 に答える 1

3

可変個引数テンプレートを使用します。

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
  }
}
于 2012-07-30T19:40:17.813 に答える