繁体   English   中英

返回带有可变数量的参数的函数指针

[英]Return a function pointer, with variable number of arguments

我想做的伪代码是:

function<bool(int)> getFunc(type) // get a function depending on what type is passed

问题是要返回的函数必须声明为静态? 结果,我无法访问对象属性。 所以我需要将它们传递给函数? 因此,要返回的原始函数可能如下所示:

bool func1(int)
bool func2(int)

现在需要注入其他需要运行的对象/参数。

bool func1(int, Class1)
bool func2(int, Class2)

那么,如何定义getFunc的返回类型? 还是有更好的方法?

更新

在上面, func*函数实际上是: has*() 例如。

hasStmtsUsing(variable)
hasVariablesUsed(stmt)

为了确定条件是否为真,它使用一个对象,例如。 uses 然后还有其他类似has*()函数等hasStmtsModifying(variable) ,使用的对象modifies usesmodifies是不同类型的对象,最初它们是对象成员,因此不需要传入。现在,由于函数是static ,因此需要传入它们。

在撰写本文时,我在想我需要某种依赖注入程序? 也许我传入DI并调用DI.getX()函数?

也许我误会了一些东西,但是,在第一个参数bind()处使用成员函数不是全部吗?

class X {
    bool f1(int);
    bool f2(int);
};

X x;
function<bool(int)> f = bind(&X::f1, &x);

下面是一个示例,说明如何在C ++ 11中使用lambda来完成此操作:

#include <cassert>
#include <functional>
#include <iostream>

struct Class1 {
};

struct Class2 {
};

bool func1(int,Class1)
{
  return true;
}

bool func2(int,Class2)
{
  return false;
}

inline std::function<bool(int)> getFunc(Class1 obj1)
{
  return [=](int x){ return func1(x,obj1); };
}

inline std::function<bool(int)> getFunc(Class2 obj2)
{
  return [=](int x){ return func2(x,obj2); };
}

int main(int,char**)
{
  Class1 obj1;
  std::function<bool(int)> f1 = getFunc(obj1);
  Class2 obj2;
  std::function<bool(int)> f2 = getFunc(obj2);
  assert(f1(0)==true);
  assert(f2(0)==false);
  return 0;
}

暂无
暂无

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

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