Convert std::variant to another std::variant with super-set of types(将 std::variant 转换为具有超类型集的另一个 std::variant)
问题描述
我有一个 std::variant
我想将其转换为另一个具有其类型超集的 std::variant
.有没有一种方法可以让我简单地将一个分配给另一个?
I have a std::variant
that I'd like to convert to another std::variant
that has a super-set of its types. Is there a way of doing it than that allows me to simply assign one to the other?
template <typename ToVariant, typename FromVariant>
ToVariant ConvertVariant(const FromVariant& from) {
ToVariant to = std::visit([](auto&& arg) -> ToVariant {return arg ; }, from);
return to;
}
int main()
{
std::variant<int , double> a;
a = 5;
std::variant <std::string, double, int> b;
b = ConvertVariant<decltype(b),decltype(a)>(a);
return 0;
}
我希望能够简单地编写 b = a
来进行转换,而不是通过这种复杂的转换设置.不会污染 std
命名空间.
I'd like to be able to simply write b = a
in order to do the conversion rather than going through this complex casting setup. Without polluting the std
namespace.
简单地写 b = a
会出现以下错误:
Simply writing b = a
gives the following error:
error C2679: binary '=': no operator found which takes a right-hand operand of type 'std::variant<int,double>' (or there is no acceptable conversion)
note: while trying to match the argument list '(std::variant<std::string,int,double>, std::variant<int,double>)'
推荐答案
这是Yakk第二个选项的实现:
This is an implementation of Yakk's second option:
template <class... Args>
struct variant_cast_proxy
{
std::variant<Args...> v;
template <class... ToArgs>
operator std::variant<ToArgs...>() const
{
return std::visit([](auto&& arg) -> std::variant<ToArgs...> { return arg ; },
v);
}
};
template <class... Args>
auto variant_cast(const std::variant<Args...>& v) -> variant_cast_proxy<Args...>
{
return {v};
}
您可能希望对其进行微调以实现转发语义.
You might want to fine tune it for forwarding semantics.
你可以看到它的使用很简单:
And as you can see its use is simple:
std::variant<int, char> v1 = 24;
std::variant<int, char, bool> v2;
v2 = variant_cast(v1);
这篇关于将 std::variant 转换为具有超类型集的另一个 std::variant的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 std::variant 转换为具有超类型集的另一个 std::variant


基础教程推荐
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 从 std::cin 读取密码 2021-01-01