Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a member function that is in all types held by std::variant?

Tags:

c++

variant

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)?

like image 643
David Avatar asked Oct 27 '25 22:10

David


1 Answers

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
}
like image 140
Deumaudit Avatar answered Oct 29 '25 15:10

Deumaudit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!