C++ Logo

std-proposals

Advanced search

[std-proposals] Return type deduction

From: Baruch Burstein <bmburstein_at_[hidden]>
Date: Wed, 9 Mar 2022 15:46:36 +0200
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.

Received on 2022-03-09 13:47:13