C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Return type deduction

From: Lénárd Szolnoki <cpp_at_[hidden]>
Date: Wed, 09 Mar 2022 14:22:51 +0000
Hi,

So what would the rule be for three return statements? The ternary operator rules are only specified for two arguments.

Personally I'm not a fan of introducing some kind of common type here.

Cheers,
Lénárd



-------- Original Message --------
From: Baruch Burstein via Std-Proposals <std-proposals_at_[hidden]>
Sent: March 9, 2022 1:46:36 PM GMT+00:00
To: std-proposals_at_[hidden]
Cc: Baruch Burstein <bmburstein_at_[hidden]>
Subject: [std-proposals] Return type deduction

Hi,
Under the current rules, if a function uses return-type deduction
(a.k.a. auto return), all the return statements must deduce to the
same type. I want to suggest to relax this rule, to match the rules
for determining the result type of the ternary operator.
For example, consider these functions:

    auto foo(bool b) {
        return b ? 1 : 2.3;
    }
    auto bar(bool b) {
        if (b) return 1;
        return 2.3;
    }

Under the current rules, foo compiles but bar gives an error about the
return type not matching in all return statements.

I want to suggest that the rule be as follows:
1. Deduce all return types of all return statements in the function that:
    a. are not brace-init-lists, and
    b. are not recursive (i.e. don't refer back to this function)
2. Deduce return type of function using the same rules as for the ?:
operator, with appropriate adjustments to account for more than 2
types (it is a technical adjustment to the wording)
3. Once return type has been deduced, allow using the function
recursively, and allow return statements using brace-init-list as-if
the return type was explicit in the function declaration.

So, with those rules, all of the following (contrived) examples would be ok:

    auto f1(bool b) {
        if (b) return 1;
        return 2.3;
    }

    auto f2(bool b) {
        if (b) return {};
        return std::string("hello");
    }

    auto f3(bool b) {
        if (b) return f3(false) + " world";
        return std::string("hello");
    }

    template <class D>
    auto scope(bool b, D&& del) {
        if (b)
            return std::unique_ptr<void, D>((void*)1, std::forward<D>(del));
        return {};
    }

I would love to hear people's thoughts on this.
-- 
Std-Proposals mailing list
Std-Proposals_at_[hidden]
https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals

Received on 2022-03-09 14:22:55