首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何声明一个接受lambda的函数?

如何声明一个接受lambda的函数?
EN

Stack Overflow用户
提问于 2010-05-30 20:20:17
回答 3查看 31.6K关注 0票数 93

我在互联网上读了很多教程,它们解释了如何在标准库(如std::find)中使用lambda,它们都非常有趣,但我找不到任何解释如何将lambda用于我自己的函数的教程。

例如:

代码语言:javascript
复制
int main()
{
    int test = 5;
    LambdaTest([&](int a) { test += a; });

    return EXIT_SUCCESS;
}

我应该如何声明LambdaTest?它的第一个参数的类型是什么?然后,我如何调用传递给它的匿名函数-例如- "10“作为其参数?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-05-30 20:25:01

考虑到除了operator()之外,您可能还希望接受函数指针和函数对象,那么您可能希望使用模板来接受带有lambda的任何参数。这就是像find这样的std函数所做的事情。它看起来像这样:

代码语言:javascript
复制
template<typename Func>
void LambdaTest(Func f) {
    f(10);
}

注意,这个定义没有使用任何c++0x特性,因此它是完全向后兼容的。只有使用lambda表达式的函数调用才是特定于c++0x的。

票数 84
EN

Stack Overflow用户

发布于 2010-05-30 20:32:05

如果您不想将所有内容都模板化,可以执行以下操作:

代码语言:javascript
复制
#include<functional> 

void LambdaTest (const std::function <void (int)>& f)
{
    ...
}
票数 78
EN

Stack Overflow用户

发布于 2014-12-24 06:35:43

我想贡献这个简单但不言自明的例子。它展示了如何将“可调用的东西”(函数、函数对象和lambda)传递给函数或对象。

代码语言:javascript
复制
// g++ -std=c++11 thisFile.cpp

#include <iostream>
#include <thread>

using namespace std;

// -----------------------------------------------------------------
class Box {
public:
  function<void(string)> theFunction; 
  bool funValid;

  Box () : funValid (false) { }

  void setFun (function<void(string)> f) {
    theFunction = f;
    funValid = true;
  }

  void callIt () {
    if ( ! funValid ) return;
    theFunction (" hello from Box ");
  }
}; // class

// -----------------------------------------------------------------
class FunClass {
public:
  string msg;
  FunClass (string m) :  msg (m) { }
  void operator() (string s) {
    cout << msg <<  s << endl; 
  }
};

// -----------------------------------------------------------------
void f (string s) {
  cout << s << endl;
} // ()

// -----------------------------------------------------------------
void call_it ( void (*pf) (string) ) {
  pf( "call_it: hello");
} // ()

// -----------------------------------------------------------------
void call_it1 ( function<void(string)> pf ) {
  pf( "call_it1: hello");
} // ()

// -----------------------------------------------------------------
int main() {

  int a = 1234;

  FunClass fc ( " christmas ");

  f("hello");

  call_it ( f );

  call_it1 ( f );

  // conversion ERROR: call_it ( [&] (string s) -> void { cout << s << a << endl; } );

  call_it1 ( [&] (string s) -> void { cout << s << a << endl; } );

  Box ca;

  ca.callIt ();

  ca.setFun (f);

  ca.callIt ();

  ca.setFun ( [&] (string s) -> void { cout << s << a << endl; } );

  ca.callIt ();

  ca.setFun (fc);

  ca.callIt ();

} // ()
票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2938571

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档