且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我们可以使用 lambda 表达式作为函数参数的默认值吗?

更新时间:2023-02-18 07:43:07

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

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); 将调用 foofoo() 是格式错误的.您需要显式调用 foo() .由于在您的情况下您使用的是 lambda 表达式,因此没有人可以调用 foo ,因为表达式的类型(在默认参数的位置)是唯一的.但是你可以这样做:

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