Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make lambdas deduce the variant return type?

This mostly theoretical since I can always spell out the return type, but I wonder if there is a way for me to tell lambda that return type should be union(std::variant) of all returns in lambda body.

#include <iostream>
#include <variant>

struct A{
    int val = 47;
};

struct B {
    float val = 4.7;
};

int main()
{
    for (int i=0;i<8;++i){
                      // can this be something like -> auto_variant  (auto_variant is some library type)
        auto var = []()->std::variant<A, B> {
            if (rand()%2 ){
                return A{};
            } else {
                return B{};
            }
        }();
        std::visit ([](const auto& val) {std::cout<< val.val << std::endl;}, var);
    }
}

note: my strong feeling is that the answer is NO, this is not possible, but I am curious if somebody knows some trick.

note2: using std::any does not fit my requirements, since I want the return type of lambda be known at compile time, instead of at runtime(with any_cast).

like image 974
NoSenseEtAl Avatar asked Feb 09 '21 13:02

NoSenseEtAl


1 Answers

You will find I'm cheating but maybe

using A_or_B = std::variant<A, B>;

then

[]() {
  if (rand()%2) {
    return A_or_B{A{}};
  } else {
    return A_or_B{B{}};
  }
}

does the trick?

like image 102
prog-fh Avatar answered Oct 05 '22 22:10

prog-fh