Search code examples
c++stdstd-variant

Call generic method for std::variant


There are two classes with methods f() under the same name and signature:

struct A {
    void f() {}
};
struct B {
    void f() {}
};

Is it possible having a std::variant<A, B> v to call this method with a single expression instead of std::visit? Like v->f()?

Note: the question is specifically about std::variant. NOT about how to solve this particular task with without it (e.g. inheritance).


Solution

  • You seem to be worried about the number of characters you have to type. Minimizing typing is not a design goal of the language. std::visit is the way to do what you want. And because this is the way there is no reason to provide a different way that would achieve the same.

    If you want the same with less typing you can always write a custom function:

    void f(auto& v) {
         std::visit( [](auto& x) { x.f(); },v );
    }
    

    Then you can call it via f(v);. Its not exactly the desired v->f(); but actually it has less characters to type.


    PS: If this is for code golf, I want to refer you to this answer I wrote https://codegolf.stackexchange.com/a/251154/114229. It is discussing the trade off between adding some code to make certain expressions shorter (the answer is specifically about using #define but the same considerations apply to writing a function).

    PPS: If this is not for code golf, I want to remind you that code is written only once, but read many times. Everybody can read std::visit(...) and there is plenty of documentation on how it works and what it does. There is zero documentation for the function f above and it has a really poor name. Readability is more important than faster typing.