c++ - 如何添加到 std::variants ?

标签 c++ c++17 variant

所以我有:

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);

live example on wandbox.org

关于c++ - 如何添加到 std::variants ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51039758/

相关文章:

delphi - 将通用 TArray 转换为 varArray

c++ - C++ 中的递归 Typedef

c++ - 在 wstring 和 string 之间转换,用 "same"方式得到不同的结果

c++ - 如何将 std::is_convertible_v 应用于一组可变参数?

c++ - 在概念定义中,是否允许在 requires 表达式之外出现替换失败?

c++ - vector::emplace_back结果两次调用析构函数

c++ - 将指向成员函数的指针传递给模板

c++ - 非递归访问自定义变量-如何优雅地返回值?

c++ - 在数组中查找 y 的 x 个连续值的最有效方法是什么?

c++ - 3个平行区域