简体   繁体   English

C ++函子和默认参数

[英]C++ functors and default parameters

I've wrote a functor library (based on the tutorial at: http://www.tutok.sk/fastgl/callback.html ). 我已经编写了一个仿函数库(基于位于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. 我知道boost具有该功能,但我不想使用它-我想自己编写。

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. 我不想使用boost或std ++的原因是因为此代码是跨平台的,将在某些没有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 你不得不收拾这件事(例如包括在模板ARGS的BinaryFunctor的返回类型,顺便说一句,我不是编的!),但这样的事情应该工作

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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