将lambda函数指定为默认参数 [英] Specifying a lambda function as default argument

查看:138
本文介绍了将lambda函数指定为默认参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将lambda分配为默认参数?我想这样做:

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);
}

但是我的编译器(Mac OS X上的g ++ 4.6) >

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

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

EDIT
这是一个编译器错误。上述代码适用于最新版本的gcc(4.7-20120225)。

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

推荐答案

您可以使用重载:

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);
}

这篇关于将lambda函数指定为默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆