Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign variant<A,B,C> from variant<C,B>?

Using = does not work.

I have code like this, but it is a "bit" ugly.

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

using namespace std;

namespace detail {
    template<typename... L, typename... R>
    void VariantAssignRec(variant<L...>* lhs, const variant<R...>&rhs, size_t rhs_idx, std::integral_constant<int, -1>) {
    }

    template<typename... L, typename... R, int get_idx>
    void VariantAssignRec(variant<L...>* lhs, const variant<R...>&rhs, size_t rhs_idx, std::integral_constant<int, get_idx> = {}) {
        assert(rhs_idx < std::variant_size_v< variant<R...>>);
        if (get_idx == rhs_idx) {
            cout << "assigning from idx " << get_idx << endl;
            *lhs = std::get<get_idx>(rhs);
            return;
        }
        else {
            std::integral_constant<int, get_idx - 1> prev_get_idx;
            VariantAssignRec(lhs, rhs, rhs_idx, prev_get_idx);
        }
    }
}
template<typename... L, typename... R>
void VariantAssign(variant<L...>* lhs, const variant<R...>&rhs) {
    detail::VariantAssignRec(lhs, rhs, rhs.index(), std::integral_constant<int, std::variant_size_v<variant<R...>>-1>{});
}


int main()
{
   std::variant<int, char, std::string> va = 'a';
   std::variant<std::string, int> vb = string("abc");
   cout << "va index is  " << va.index() << endl; 
   cout << "vb index is  " << vb.index() << endl; 
   VariantAssign(&va, vb);
   cout << "va index now should be 2, and it is  " << va.index() << endl; 
   vb = 47;
   VariantAssign(&va, vb);
   cout << "va index now should be 0, and it is  " << va.index() << endl; 
}

I am using VS so no if constexpr but I am looking for general C++17 solution regardless of VC++ lacking support.

like image 958
NoSenseEtAl Avatar asked Jan 30 '23 02:01

NoSenseEtAl


1 Answers

Just use a visitor:

std::variant<A, B, C> dst = ...;
std::variant<B, C> src = B{};

std::visit([&dst](auto const& src) { dst = src; }, src);

If there is a type in src that isn't assignable to dst, this won't compile - which is probably the desired behavior.

If you end up using this pattern semi-often, you could move the assigner into its own function:

template <class T>
auto assignTo(T& dst) {
    return [&dst](auto const& src) { dst = src; };
}

std::visit(assignTo(dst), src);
like image 145
Barry Avatar answered Feb 05 '23 17:02

Barry