Lambda Expression vs Functor in C++

后端 未结 8 779
予麋鹿
予麋鹿 2020-12-05 00:01

I wonder where should we use lambda expression over functor in C++. To me, these two techniques are basically the same, even functor is more elegant and cleaner tha

8条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-05 00:21

    Conceptually, the decision of which to use is driven by the same criterion as using a named variable versus a in-place expression or constant...

    size_t length = strlen(x) + sizeof(y) + z++ + strlen('\0');
    ...
    allocate(length);
    std::cout << length;
    

    ...here, creating a length variable encourages the program to consider it's correctness and meaning in isolation of it's later use. The name hopefully conveys enough that it can be understood intuitively and independently of it's initial value. It then allows the value to be used several times without repeating the expression (while handling z being different). While here...

    allocate(strlen(x) + sizeof(y) + z++ + strlen('\0'));
    

    ...the total code is reduced and the value is localised at the point it's needed. The only thing to "carry forwards" from a reading of this line is the side effects of allocation and increment (z), but there's no extra local variable with scope or later use to consider. The programmer has to mentally juggle less state while continuing their analysis of the code.

    The same distinction applies to functions versus inline statements. For the purposes of answering your question, functors versus lambdas can be seen as just a particular case of this function versus inlining decision.

提交回复
热议问题