Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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();
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading