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
).
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With