c++ - std::variant<>::get() 不能用 Apple LLVM 10.0 编译

标签 c++ c++17 llvm-clang variant

我正在使用 C++17 std::variant 类型并尝试编译 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,但出现编译器错误:

Call to unavailable function 'get': introduced in macOS 10.14

'bad_variant_access' is unavailable: introduced in macOS 10.14

这在两个方面令人惊讶:如果支持 std::variant 它应该编译并且关于 macOS 10.14 的提示很奇怪,因为我在那个版本上并且它没有任何关系使用受支持的 C++ 方言(项目的部署目标是 10.14)。

这是我做错了什么还是 clang 中的错误?

最佳答案

全部std::variant可能抛出 std::bad_variant_access 的功能在标准头文件中标记为从 macOS 10.14(以及相应的 iOS、tvOS 和 watchOS)开始可用。这是因为虚拟 std::bad_variant_access::what()方法不是inline并因此在 libc++.dylib 中定义(由操作系统提供)。

如果你想使用std::variant在旧操作系统上运行的应用程序中,只需使用 std::get_if .在你的例子中:

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

您也可以通过 w.index() 提前查询和 std:: holds_alternative <int>(w) .

编辑: 另见我的 answerstd::visit 的类似问题(不幸的是,有一个不太方便的解决方法)

关于c++ - std::variant<>::get() 不能用 Apple LLVM 10.0 编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52521388/

相关文章:

c++ - 将 uint32_t 转换为 uint64_t 会产生不同的值?

c++ - 带有 Boost::Spirit 的自定义跳过解析器

c++ - 相同的类和实例名称

c++ - 对于像 ETX/STX 对这样的多个字符,是否有类似于 std::quote 的东西

c++ - 从 FloatingLiteral/APFloat 获取原始解析数字

android - OpenMAX AL 因信号 6 (SIGABRT) 而崩溃。媒体服务器死机

c++ - 获取非专用 std::vector<bool> 容器的标准方法

类中的 C++17 变体<any>

c++ - 在 Clang 中,编写自定义 ASTMatcher 时可以访问 SourceManager 吗?