Lambda functions as base classes

前端 未结 2 837
[愿得一人]
[愿得一人] 2020-12-02 09:23

Playing around with Lambdas I found an interesting behaviour that I do not fully understand.

Supose I have a struct Overload that derives from 2 templat

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-02 09:36

    In addition to operator(), a the class defined by a lambda can (under the right circumstances) provide a conversion to a pointer to function. The circumstance (or at least the primary one) is that the lambda can't capture anything.

    If you add a capture:

    auto f1 = get(
                  []() { std::cout << "lambda1::operator()()\n"; },
                  [i](int) { std::cout << "lambda2::operator()(int)\n"; }
                  );
    f1();
    f1(2);
    

    ...the conversion to pointer to function is no longer provided, so trying to compile the code above gives the error you probably expected all along:

    trash9.cpp: In function 'int main(int, char**)':
    trash9.cpp:49:9: error: no match for call to '(Overload, main(int, char**):: >) (int)'
    trash9.cpp:14:8: note: candidate is:
    trash9.cpp:45:23: note: main(int, char**)::
    trash9.cpp:45:23: note:   candidate expects 0 arguments, 1 provided
    

提交回复
热议问题