有没有办法将一些函数或运算符作为参数提供?

cnd*_*cnd 2 c++ boost c++11

有没有办法为C++带来一些函数式编程,我想将一些LAMBDA函数或运算符作为参数传递给另一个函数.

例如 :

void test(DWORD foo)
{ 
  try { __asm { call foo; } }  // very weird way, don't think that could work
  catch (...) { () } 
}
Run Code Online (Sandbox Code Playgroud)

要么 :

void test2(DWORD foo)
{ 
  someconnection.Open();
   __asm { call foo; }  // very weird way, don't think that could work
  someconnection.Close();
}
Run Code Online (Sandbox Code Playgroud)

和用法一样:

int main ()
{
  ...
  dosomething();
  ...
  void operator()(int n) // lambda expression, not sure if that correct way creating them
  {
     dosomething();
     dosomethingelse();
  }
  test ( *operator(5) ) // here is what I want
  test2 ( *operator(10) ) // here is what I want
  ...
  dosomethingelse();
  ...
}
Run Code Online (Sandbox Code Playgroud)

我正在使用Visual Studio 2010并且不确定我是否可以在那里使用C++ 0x但是如果可以做我想做的事情我可以使用boost.

那么有一些方法可以做到吗?

Jon*_*Jon 6

你可以通过制作例如testa 的参数std::tr1::function:

void test(std::tr1::function<void(DWORD)> func) {
    func(0);
}
Run Code Online (Sandbox Code Playgroud)

你可以用函数,成员函数甚至lambda来调用它:

test([](DWORD param) { return; });
Run Code Online (Sandbox Code Playgroud)

  • 注意:由于这是标记的C++ 0x,因此不需要`tr1`命名空间. (2认同)