c++varianttype-deduction

Automatic return type deduction of std::variant for auto functions in C++


For this code:

struct A {};
struct B {};

auto f() -> std::variant<A, B>
{
    if (true) return A();
    return B();
}

Is it possible for a compiler to automatically deduce return type as std::variant<A,B>? Just so return type declaration can be omitted:

auto f() // std::variant<A, B> deduced by compiler
{
    if (true) return A();
    return B();
}

Solution

  • No, it is not possible.

    Automatic return type deduction works only when all you return statements return the same type, and here A and B are different.

    It would be very hard (if not impossible) to define the rules in any other way.

    In your case for example, there could be other types that can all be constructed from either an A or a B, for example:

    1. std::variant<A, B, std::monostate> (or any other std::variant that can contain A or B or any other type).
    2. std::any.

    Also there could be some custom class that has constructors - one accepting an A and one accepting a B.

    All these examples demonstrate why expecting the compiler to deduce variant<A, B> as a return type is a bit too much.