【问题标题】:C++ functors and default parametersC++ 函子和默认参数
【发布时间】:2011-11-21 17:54:17
【问题描述】:

我已经编写了一个函子库(基于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的平台上使用。

【问题讨论】:

  • 您有问题吗?
  • C++11 中的标准库也有同样的功能。您确定不想使用 C++11,或者使用 boost 来练习使用新的标准库功能吗?

标签: c++ templates boost metaprogramming functor


【解决方案1】:

如果你真的不想(或不能)使用已经解决了这个问题的其他人的工作,那么函子的构造函数如何保留你想要传递的参数?!?

你必须整理一下(例如,在模板 args 中包含 BinaryFunctor 的返回类型,顺便说一句,我还没有编译它!)但是 like 应该可以

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-09
    • 2013-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-07
    • 1970-01-01
    相关资源
    最近更新 更多