gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:12:29 24 4
gpt4 key购买 nike

我正在使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com