如何将 std::variant 减为一个值?

How do I reduce an std::variant to one value?

我有一个 C++ 17 std::variant。如何使用 lambda 将其减少为一种类型的单个实例?

我正在寻找这样的东西:

std::variant<int, std::string> v = getIntOrString();

std::string x = reduce(
  v, 
  [](int i) {
    return "It's an int: " + std::to_string(i);
  }, 
  [](std::string i) {
    return "It's a string: " + i;
  });

基于 cppreference 的示例,您将使用 std::visit:

#include <variant>
#include <string>
#include <iostream>

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

int main() {
    using v_type = std::variant<int, std::string>;
    v_type v1{1}, v2{"2"};

    auto v_to_str = overloaded{
        [](int i) { return std::to_string(i) + " was an int"; },
        [](std::string const& s) { return s + " was already a string"; }
    };

    std::cout << std::visit(v_to_str, v1) << '\n'
              << std::visit(v_to_str, v2);

}

Live Example