简体   繁体   中英

C++ functors and default parameters

I've wrote a functor library (based on the tutorial at: http://www.tutok.sk/fastgl/callback.html ).

Currently, I can write the following code:

class MyClass
{
public:
    void Test(int a,int b);
};

MyClass c;
Functor2<void,int,int> f=makeFunctor(c,&MyClass::Test);
...
f(1,2);

I would like to add another feature so I can bind parameters with the actual function (to pass it forward), so for example:

Functor0<void> f=makeFunctor(c,&MyClass::Test,3,4);
...
f(); // this will use the default parameters 3,4

I know that boost has that functionality, but I don't want to use that - I would like to write it myself.

My question is how to define a functor where I can also pass default arguments to be used in the call itself. The reason I don't want to use boost nor std++ is because this code is cross platform and will be used on some platforms which do not have boost.

If you really don't want (or can't) use the work of other people who have already solved this problem, how about a constructor for the functor to keep the parameters you want to pass?!?

You'd have to tidy this up (eg. to include the return type of the BinaryFunctor in the template args, and btw I've not compiled it!) but something like this should work

class MyClass
{
public:
    void Test(int a,int b);
};

template <class BinaryFunctor, class Arg1, class Arg2>
class Functor0
{
  public:
    Arg1 _a;
    Arg2 _b;
    BinaryFunctor _func;

    void operator() ()
    {
      _func(_a, _b);
    }    
};


MyClass c;
Functor2<void,int,int> f=makeFunctor(c,&MyClass::Test);
f(1,2);


Functor0<Functor,int,int> f2(f,3,4);
f2();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM