abseil-cpp icon indicating copy to clipboard operation
abseil-cpp copied to clipboard

[FR]: Add MatchVariant helper for std::visit + Overload

Open hocheung-chromium opened this issue 7 months ago • 1 comments

Describe the issue

Motivation

When using absl::Overload with std::visit, the syntax requires constructing an explicit Overload object:

std::visit(absl::Overload{ 
    [](int) { ... },
    [](std::string) { ... }
}, my_variant);

Adding a MatchVariant helper would simplify this to:

absl::MatchVariant(my_variant,
    [](int) { ... },
    [](std::string) { ... });

Proposed implementation

template <typename Variant, typename... T>
auto MatchVariant(const Variant& v, T... args) {
    return std::visit(Overload{args...}, v);
}

Steps to reproduce the problem

N/A

What version of Abseil are you using?

Latest version

What operating system and version are you using?

Debian testing

What compiler and version are you using?

clang

What build system are you using?

Ninja

Additional context

No response

hocheung-chromium avatar Jun 11 '25 02:06 hocheung-chromium

@jbandela

FYI I'm asking around for feedback on this proposal.

derekmauro avatar Jun 12 '25 13:06 derekmauro

I am not sure it has enough upside to justify the cost of putting it in Abseil.

Match is somewhat of an overloaded term with pattern matching and may imply more than it does. The original use of Overload with std::visit is pretty self-explanatory with the std definition of visit.

jbandela avatar Aug 01 '25 15:08 jbandela

Yes, after some time of investigation, I agree with your opinion. I think we can close this issue.

hocheung-chromium avatar Aug 01 '25 16:08 hocheung-chromium

Thất bại là mẹ của thành công

VODINHCUONG avatar Aug 02 '25 18:08 VODINHCUONG