[go: up one dir, main page]

Skip to content

Latest commit

 

History

History
66 lines (47 loc) · 1.28 KB

344.md

File metadata and controls

66 lines (47 loc) · 1.28 KB
Info

Example

// C++23
std::visit(overload{
  [](int i){ std::print("i={}\n", i); },
  [](std::string s){ std::print("s={:?}\n", s); }
}, value);

// C++26
value.visit(overload{
  [](int i){ std::print("i={}\n", i); },
  [](std::string s){ std::print("s={:?}\n", s); }
});

https://godbolt.org/z/dMf9b5xMq

Puzzle

  • Can you implement member visit for variant?
// TODO: variant

int main() {
    constexpr variant<int, double, float> value = 42;

    static_assert(42 == value.visit(overload{
        [](int i) { return i; },
        [](auto)  { return 0; }
    }));
}

https://godbolt.org/z/zcqj553dc

Solutions

template <class... Ts>
struct overload : Ts... {
    using Ts::operator()...;
};
template <class... Ts>
overload(Ts...) -> overload<Ts...>;

template <class... Ts>
struct variant : std::variant<Ts...> {
    using std::variant<Ts...>::variant;

    constexpr auto visit(auto f) const { return std::visit(f, *this); }
};

https://godbolt.org/z/EGMvP963G