Search code examples
c++variadic-templatesvariant

How do I move the value of a variant<Ts...> into a variant<T,Ts...>?


Is there an easy way to move the data contained in some std::variant<Ts...> into an std::variant<T,Ts...>?

I suppose there is the option to switch over all types in Ts... with an extra class template, but I wonder if there is a more elegant in-place way to do this.

Example:

template <typename T, typename... Ts>
std::variant<T,Ts...> use(std::optional<T>&& opt, std::variant<Ts...>&& var) {
  if (opt.has_value()) return *opt;
  else return magic<T,T...>(var);
}

Solution

  • You can visit and then construct the new variant type:

    return std::visit([](auto&& arg) -> std::variant<T, Ts...> {
        return std::forward<decltype(arg)>(arg);
    }, std::move(var));