Strange bracket-parentheses notation in C++, looking somewhat like a for each loop

后端 未结 3 1497
醉梦人生
醉梦人生 2021-01-22 08:33

So this is how the code looks:

auto generateHash = [](std::vector &files) -> std::shared_ptr {
    // Other code here
}


        
相关标签:
3条回答
  • 2021-01-22 09:13

    This is lambda function, see e.g. http://en.cppreference.com/w/cpp/language/lambda.

    0 讨论(0)
  • 2021-01-22 09:17

    What does this mean?

    It's a lambda - a function object. You can call it like a function with a a vector of files (passed by mutable reference, for some weird reason), and it a returns string (managed by a shared pointer, for some weird reason).

    std::vector<File> files = get_some_files();
    std::shared_ptr<std::string> hash = generateHash(files); // call the lambda
    

    Is it a for each loop?

    No. That looks like

    for (auto thing : sequence) {/* code */}
    

    What do the brackets in the beginning do?

    They signify that it's a lambda. They can contain the capture list of local variables that you want to make available to the code inside the lambda.

    What does the arrow mean?

    That's a trailing return type. In C++11, you can use that syntax with normal functions if you want; but it's the only way to specify a lambda's return type.

    I can't find it in the C++ reference.

    It's right here: http://en.cppreference.com/w/cpp/language/lambda

    0 讨论(0)
  • 2021-01-22 09:23

    This is a C++11 lambda function, for a tutorial on how they work, you can look at this, else for a pure reference you can look at this.

    In your case it defines an anonymous function that takes in std::vector<File> &files and returns std::shared_ptr<std::string>, and assigns this function to generateHash. the auto keyword tells the compiler to derive the type of generateHash (it this case it makes for a simple shorthand). the empty brackets ([]) means that the lambda doesn't capture and local variables for use within the lambda.

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