Reputation:
As per the documatation(What is a lambda expression in C++11?), The return type of the lambda could be deduced in this code. I could not get the idea how it could be done?
void func4(std::vector<double>& v)
{
std::transform(v.begin(), v.end(), v.begin(),
[](double d) { return d < 0.00001 ? 0 : d; }
);
}
But,it cannot be deduced in this example, why?
void func4(std::vector<double>& v) {
std::transform(v.begin(), v.end(), v.begin(),
[](double d) {
if (d < 0.0001) {
return 0;
} else {
return d;
}
});
}
Upvotes: 3
Views: 102
Reputation: 122460
Sloppy speaking, the ternary operator has some built-in conversion to a common type. You can read on cppreference how the type of the result is determined. The details are rather involved, so i'll put it in plain English: The result of d < 0.00001 ? 0 : d;
is double
.
In the no-conditional version one branch returns an int
the other a double
, hence the return type cannot be deduced.
Upvotes: 4