从变体<c,b>中分配变体<a,b,c>?

时间:2017-06-29 04:51:20

标签: c++ c++17 boost-variant

使用=不起作用。

我有这样的代码,但它是一个&#34; bit&#34;难看。

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

我正在使用VS所以没有if constexpr但我正在寻找通用的C ++ 17解决方案,无论VC ++缺乏支持。

2 个答案:

答案 0 :(得分:6)

只需使用访问者:

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

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

如果src中的某个类型无法分配给dst,则无法编译 - 这可能是所需的行为。

如果您最终半经常使用此模式,则可以将分配器移动到其自己的函数中:

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

std::visit(assignTo(dst), src);

答案 1 :(得分:0)

您可以使用访问者:

struct overload_priority_low{};
struct overload_priority_high : overload_priority_low{};

template <typename V>
struct AssignTo
{
private:
    V& v; 

public:
    explicit AssignTo(V& v) : v(v) {}

    template <typename T>
    void operator () (T&& t) const
    {
        assign(std::forward<T>(t), overload_priority_high{});   
    }

private:

    template <typename T>
    auto assign(T&& t, overload_priority_high) const
    -> decltype(this->v = std::forward<T>(t), void())
    {
        v = std::forward<T>(t);
    }

    template <typename T>
    void assign(T&& t, overload_priority_low) const
    {
        throw std::runtime_error("Unsupported type");
    }

};

使用方法:

int main() {
    std::variant<int, char> v = 0;
    std::variant<int, char, std::string> v2 = 42;

    std::visit(AssignTo(v), v2);
}

Demo