locked
C++ Lambda Function Callbacks RRS feed

  • Question

  • Hey guys,

     

    First time on here...Have a question regarding C++ lambda functions in VS2010. Been playing around lately, and I can't quite figure out how it is possible to create a function which would accept a lambda expression as an argument...If at all. I've realized that you can store a lambda expression using the auto keyword:

     

    auto callback = [](void*){ cout << "CALLED!" << endl; };

     

    But I can't seem to figure out what type I would use in a function signature to actually pass one in...I feel like there HAS to be a way. Help please?

     

    Thanks in advance.

     

    ---Dan

    Sunday, April 25, 2010 7:11 PM

Answers

  • Daniel M. Katz wrote:
    > First time on here...Have a question regarding C++ lambda functions in VS2010. Been playing around lately, and I can't quite
    > figure out how it is possible to create a function which would accept a lambda expression as an argument...If at all.
     
    template <typename F>
    void call(F f) { f(); }
     
    call([](){});
     
    Alternatively, you can accept std::function as a parameter:
     
    void call(std::function<void()> f) { f(); }
     
    std::function can wrap any callable object, including a lambda.
    --
    Igor Tandetnik
    • Proposed as answer by ildjarn Tuesday, April 27, 2010 5:01 PM
    • Marked as answer by Yi Feng Li Friday, April 30, 2010 2:10 AM
    Sunday, April 25, 2010 8:21 PM

All replies

  • Daniel M. Katz wrote:
    > First time on here...Have a question regarding C++ lambda functions in VS2010. Been playing around lately, and I can't quite
    > figure out how it is possible to create a function which would accept a lambda expression as an argument...If at all.
     
    template <typename F>
    void call(F f) { f(); }
     
    call([](){});
     
    Alternatively, you can accept std::function as a parameter:
     
    void call(std::function<void()> f) { f(); }
     
    std::function can wrap any callable object, including a lambda.
    --
    Igor Tandetnik
    • Proposed as answer by ildjarn Tuesday, April 27, 2010 5:01 PM
    • Marked as answer by Yi Feng Li Friday, April 30, 2010 2:10 AM
    Sunday, April 25, 2010 8:21 PM
  • Ah-hah! The std::function solution was exactly what I was looking for...I had a feeling that I would probably be making use of the functor nature of the lambda expression, but I'm not very familiar with their usage. Thanks a lot!
    Sunday, April 25, 2010 8:41 PM
  • Note that using std::function has significant overhead compared to the template<typename F> route as it makes use of type erasure and RTTI internally at runtime, whereas the template will be statically resolved at compile time. I.e., if performance matters, don't use std::function for this.
    Tuesday, April 27, 2010 5:00 PM