I'm reading C++ primer 5th edition, chapter 10(lambdas expressions), Here is a program that is intended to replace negative values in a vector by their absolute value.
transform(vi.begin(), vi.end(), vi.begin(),
[](int i) { if (i < 0) return -i; else return i; });
The author says that:
This code won't compile because the lambda infers the return type as
voidbut we returned a value and to fix this, we must use a trailing return type.
But when I compile this code with GNU GCC Compiler on Windows, it works well.
The author also says that:
This version compile because we need not specify the return type, because that type can be inferred from the type of the conditional operator.
transform(vi.begin(), vi.end(), vi.begin(),
[](int i) { return i < 0 ? -i : i; });
So, my questions are:
- Why with the first version, the lambda infers the return type as void and why does GNU GCC compiler accept this.*(I thought that maybe because of optimizations).?
- Why with the second version, the return type can be inferred from the type of the conditional operator?
Aucun commentaire:
Enregistrer un commentaire