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

How do I assign a lambda as default argument? I would like to do this:

int foo(int i, std::function<int(int)> f = [](int x) -> int { return x / 2; })
{
    return f(i);
}

but my compiler (g++ 4.6 on Mac OS X) complains:

error: local variable 'x' may not appear in this context

EDIT: Indeed, this was a compiler bug. The above code works fine with a recent version of gcc (4.7-20120225).

See Question&Answers more detail:os

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

1 Answer

You could use overloading:

int foo(int i)
{
    return foo(i, [](int x) -> int { return x / 2; });
}

int foo(int i, std::function<int(int)> f)
{
    return f(i);
}

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

548k questions

547k answers

4 comments

86.3k users

...