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

时间:2017-06-08 07:04:27

标签: c++ lambda discriminated-union

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

我正在寻找类似的东西:

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;
  });

1 个答案:

答案 0 :(得分:3)

在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