所以我有:
typedef std::variant<int,float,std::string> VarType;
我希望能够做到:
VarType a = 1;
VarType b = 1;
VarType c = a + b;
当类型混合时,抛出异常很酷。
最佳答案
VarType c = std::get<int>(a) + std::get<int>(b);
更一般:
VarType c = std::visit([](auto x, auto y) -> VarType
{
if constexpr(!std::is_same_v<decltype(x), decltype(y)>)
{
throw;
}
else
{
return x + y;
}
}, a, b);
关于c++ - 如何添加到 std::variants ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51039758/