Hi,
Why do these semantically identical pieces of code have different syntax rules?
template <typename Map, typename Lookup>
auto find(Map &map, const Lookup &key)
{
const auto it = map.find(key);
if (it == map.end())
return std::nullopt;
else
return std::optional{*it}; // error: inconsistent deduction for auto return type
}
template <typename Map, typename Lookup>
auto find(Map &map, const Lookup &key)
{
const auto it = map.find(key);
return it == map.end() ? std::nullopt : std::optional{*it}; // OK, -> std::optional<Map::value_type>
}
iow: Why do auto return types have to have identical types, and don't just use the rules for the ternary operator?
And why, in the first case, can I not say
auto find(Map &map, const Lookup &key) -> std::optional
{
iow: why doesn't ctor template argument deduction work for trailing return types?
Is/was this a conscious decision against, or would a proposal adding/changing these be welcome?
Thanks,
Marc
--
You received this message because you are subscribed to the Google Groups "ISO C++ Standard - Future Proposals" group.
To unsubscribe from this group and stop receiving emails from it, send an email to std-proposals+unsubscribe@isocpp.org.
To post to this group, send email to std-pr...@isocpp.org.
To view this discussion on the web visit https://groups.google.com/a/isocpp.org/d/msgid/std-proposals/7bf0d2563477e89a8faa3ca2daa18f67%40kdab.com.
On 26 September 2017 at 00:53, Marc Mutz <marc...@kdab.com> wrote:Hi,
Why do these semantically identical pieces of code have different syntax rules?
template <typename Map, typename Lookup>
auto find(Map &map, const Lookup &key)
{
const auto it = map.find(key);
if (it == map.end())
return std::nullopt;
else
return std::optional{*it}; // error: inconsistent deduction for auto return type
}
template <typename Map, typename Lookup>
auto find(Map &map, const Lookup &key)
{
const auto it = map.find(key);
return it == map.end() ? std::nullopt : std::optional{*it}; // OK, -> std::optional<Map::value_type>
}
iow: Why do auto return types have to have identical types, and don't just use the rules for the ternary operator?Because some people thought it more important to allow self-recursive calls after the first return statement:auto f(int n) {if (n <= 1) return 1;return n * f(n - 1); // ok to call f here, return type already deduced}FWIW, I think we made the wrong tradeoff here, but this decision is unlikely to be reconsidered now.
(We could use the ternary operator rules up until the first recursive use of the function within itself, but that risks major confusion and surprises when a recursive function is refactored and its return statements are reordered...)And why, in the first case, can I not say
auto find(Map &map, const Lookup &key) -> std::optional
{
iow: why doesn't ctor template argument deduction work for trailing return types?An overabundance of conservatism. I expect this restriction will be relaxed as soon as someone argues for it in committee.