I have a variable with the following type:
std::variant<std::monostate, first_custom_type, second_custom_type> var;
where both first_custom_type and second_custom_type have a function called func() which I want to execute after creating var.
Is there a way to just call func() without having to check what type var is holding (e.g., with std::get)?
This can easily be done using std::visit. The only cornercase is std::monostate, but it can easily be avoided with overloded helper struct(example of whitch is in the link above)
struct s1{
void func()
{
std::cout << "1";
}
};
struct s2{
void func()
{
std::cout << "2";
}
};
template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
// explicit deduction guide (not needed as of C++20)
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;
int main()
{
std::variant<s1, s2, std::monostate> var1 = s1{};
std::variant<s1, s2, std::monostate> var2 = s2{};
std::variant<s1, s2, std::monostate> var3 = std::monostate{};
auto functor = overloaded {
[](std::monostate) {},
[](auto& arg) {arg.func();}
};
std::visit(functor, var1); // 1
std::visit(functor, var2); // 2
std::visit(functor, var3); // nothing
}
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