我们可以使用lambda表达式作为函数参数的默认值吗? [英] Can we use a lambda-expression as the default value for a function argument?

查看:122
本文介绍了我们可以使用lambda表达式作为函数参数的默认值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

参考C ++ 11规范(5.1.2.13):


A lambda-expression 不会隐含或显式地捕获任何实体。

[示例:

  void f2(){
int i = 1;
void g1(int =([i] {return i;})()); //形式
void g2(int =([i] {return 0;})()); //形成的
void g3(int =([=] {return i;})()); //形成的
void g4(int =([=] {return 0;})()); // OK
void g5(int =([] {return sizeof i;})()); // OK
}

但是,我们还可以使用lambda表达式本身作为函数参数的默认值吗?


$ p
$ b



< b $ b

例如

  template< typename functor> 
void foo(functor const& f = [](int x){return x;})
{
}


解决方案

是的。在这方面,lambda表达式与其他表达式(例如, 0 )没有区别。但请注意,扣除不使用默认参数。换句话说,如果您声明

  template< typename T> 
void foo(T = 0);

然后 foo(0); foo< int> 但是 foo()您需要显式调用 foo< int>()。因为在你的情况下你使用一个lambda表达式,因为表达式的类型(在默认参数的站点)是唯一的,所以可以调用 foo 。但是你可以这样做:

  //可能隐藏在一个细节命名空间或一些这样的
auto default_parameter = [] int x){return x; };

template<
typename Functor = decltype(default_parameter)
>
void foo(Functor f = default_parameter);


Refering to the C++11 specification (5.1.2.13):

A lambda-expression appearing in a default argument shall not implicitly or explicitly capture any entity.
[ Example:

void f2() {
    int i = 1;
    void g1(int = ([i]{ return i; })()); // ill-formed
    void g2(int = ([i]{ return 0; })()); // ill-formed
    void g3(int = ([=]{ return i; })()); // ill-formed
    void g4(int = ([=]{ return 0; })()); // OK
    void g5(int = ([]{ return sizeof i; })()); // OK
}

—end example ]

However, can we also use a lambda-expression itself as the default value for a function argument?

e.g.

template<typename functor>
void foo(functor const& f = [](int x){ return x; })
{
}

解决方案

Yes. In this respect lambda expressions are no different from other expressions (like, say, 0). But note that deduction is not used with defaulted parameters. In other words, if you declare

template<typename T>
void foo(T = 0);

then foo(0); will call foo<int> but foo() is ill-formed. You'd need to call foo<int>() explicitly. Since in your case you're using a lambda expression nobody can call foo since the type of the expression (at the site of the default parameter) is unique. However you can do:

// perhaps hide in a detail namespace or some such
auto default_parameter = [](int x) { return x; };

template<
    typename Functor = decltype(default_parameter)
>
void foo(Functor f = default_parameter);

这篇关于我们可以使用lambda表达式作为函数参数的默认值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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