Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I read on the internet many tutorials that explained how to use lambdas with the standard library (such as std::find), and they all were very interesting, but I couldn't find any that explained how I can use a lambda for my own functions.

For example:

int main()
{
    int test = 5;
    LambdaTest([&](int a) { test += a; });

    return EXIT_SUCCESS;
}

How should I declare LambdaTest? What's the type of its first argument? And then, how can I call the anonymous function passing to it - for example - "10" as its argument?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
172 views
Welcome To Ask or Share your Answers For Others

1 Answer

Given that you probably also want to accept function pointers and function objects in addition to lambdas, you'll probably want to use templates to accept any argument with an operator(). This is what the std-functions like find do. It would look like this:

template<typename Func>
void LambdaTest(Func f) {
    f(10);
}

Note that this definition doesn't use any c++0x features, so it's completely backwards-compatible. It's only the call to the function using lambda expressions that's c++0x-specific.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...