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
).
std::variant<A, B>
. Maybe with reflection (But I doubt also we can do that). – Homogeneitystd::variant<A, B>
and notstd::variant<B, A>
? – Alumnusstd::variant
so deduction of return value of lambda is not a problem. Note this is my personal practice which I'm finding quite useful, so if you do not like it do not complain on it. – Fret