Can we use a lambda-expression as the default value for a function argument?

前端 未结 1 1549
北恋
北恋 2020-12-09 17:03

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

A lambda-expression appearing in a default argument shall not implicitly or explicitly capt

1条回答
  •  心在旅途
    2020-12-09 17:41

    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
    void foo(T = 0);
    

    then foo(0); will call foo but foo() is ill-formed. You'd need to call foo() 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);
    

    0 讨论(0)
提交回复
热议问题