问题
So this is how the code looks:
auto generateHash = [](std::vector<File> &files) -> std::shared_ptr<std::string> {
// Other code here
}
What does this mean? Is it a for each loop? What do the brackets in the beginning do? What do the parentheses do? What does the arrow mean? I can't compile it because of no C++11 compiler, and I can't find it in the C++ reference.
回答1:
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
回答2:
This is lambda function, see e.g. http://en.cppreference.com/w/cpp/language/lambda.
回答3:
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.
来源:https://stackoverflow.com/questions/22038633/strange-bracket-parentheses-notation-in-c-looking-somewhat-like-a-for-each-lo