How should I define a std::function variable with default arguments?

后端 未结 4 1072
有刺的猬
有刺的猬 2021-02-07 08:48

To set a std::function variable to a lambda function with default argument I can use auto as in:

auto foo = [](int x = 10){cout << x <<          


        
4条回答
  •  忘了有多久
    2021-02-07 09:19

    In C++20 you will be able to do this:

    struct foo {
        decltype([](int a = 10){std::cout << a << '\n';}) my_lambda{};
    };
    
    int main() {
        foo f;
        f.my_lambda();
        f.my_lambda(5);
    }
    

    Live on Godbolt

    It does look a bit strange, but it works just fine.

    What makes this possible is the ability to use lambdas in unevaluated contexts and default construct stateless lambdas.

提交回复
热议问题