我正在使用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,但是我遇到编译器错误:
调用不可用的函数'get':在macOS 10.14中引入
和
'bad_variant_access'不可用:在macOS 10.14中引入
这有两个方面令人惊讶:如果支持std::variant
它应该编译,并且关于macOS 10.14的提示很奇怪,因为我在那个版本上并且它与支持的C ++方言无关(并且项目的部署目标是10.14 )。
这是我做错了还是铿锵的错误?
所有可能引发std::variant
的std::bad_variant_access
功能都标记为可用,从标准头文件中的macOS 10.14(以及相应的iOS,tvOS和watchOS)开始。这是因为虚拟std::bad_variant_access::what()
方法不是inline
,因此在libc++.dylib
中定义(由OS提供)。
如果你想在旧操作系统上运行的应用程序中使用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)
查询。
编辑:另请参阅我的answer与std::visit
类似的问题(不幸的是有一个不太方便的解决方法)
事实证明,该项目设置为macOS 10.14,但不是实际的构建目标,仍然是10.13。一旦我恢复它继承部署目标,测试代码就开始编译了。
考虑到XCode 10(以及LLVM 10.0)可以安装并用于在10.13上构建C ++ 17应用程序,这是一个有趣的转折。