C++函子和默认参数

发布于 2024-12-17 10:07:01 字数 663 浏览 5 评论 0原文

我写了一个函子库(基于以下教程: http://www.tutok.sk /fastgl/callback.html)。

目前,我可以编写以下代码:

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

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

我想添加另一个功能,以便我可以将参数与实际函数绑定(以将其转发),例如:

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

我知道 boost 有该功能,但我不想要使用它 - 我想自己写它。

我的问题是如何定义一个函子,我还可以传递要在调用本身中使用的默认参数。我不想使用 boost 也不想使用 std++ 的原因是因为此代码是跨平台的,并且将在某些没有 boost 的平台上使用。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

如果您真的不想(或不能)使用已经解决此问题的其他人的工作,那么函子的构造函数来保留您想要传递的参数怎么样?!?

你必须整理一下(例如,在模板参数中包含 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();

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();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文