代码之家  ›  专栏  ›  技术社区  ›  Mike Lischke

std::variant<>::get()不使用Apple LLVM 10.0编译

  •  2
  • Mike Lischke  · 技术社区  · 8 年前

    我正在玩C++ 17的STD::变量类型,并尝试编译 cppreference example code 对于 get() :

    #include <variant>
    #include <string>
    
    int main()
    {
        std::variant<int, float> v{12}, w;
        int i = std::get<int>(v);
        w = std::get<int>(v);
        w = std::get<0>(v); // same effect as the previous line
    
    //  std::get<double>(v); // error: no double in [int, float]
    //  std::get<3>(v);      // error: valid index values are 0 and 1
    
        try {
          std::get<float>(w); // w contains int, not float: will throw
        }
        catch (std::bad_variant_access&) {}
    }
    

    在XCode 10中。我的项目被设置为C++ 17,但是我得到编译器错误:

    对不可用函数“get”的调用:在macOS 10.14中引入

    和

    “bad\u variant\u access”不可用:在macOS 10.14中引入

    这在两个方面令人惊讶:如果 std::variant

    这是我做错了什么还是叮当声中的虫子?

    2 回复  |  直到 7 年前
        1
  •  23
  •   Tobi    7 年前

    全部 std::variant 可能引发 std::bad_variant_access std::bad_variant_access::what() 方法无效 inline libc++.dylib (由操作系统提供)。

    标准::变量 在旧操作系统上运行的应用程序中,只需使用 std::get_if

    if (auto* p = std::get_if<int>(&w)) {
      // use *p
    } else {
      // error handling
    }
    

    您也可以提前与 w.index() std:: holds_alternative <int>(w) .

    编辑 也看到我的 answer std::visit (不幸的是,解决方法不太方便)

        2
  •  3
  •   Mike Lischke    7 年前