我正在尝试使用C++17的std::variant类型,并尝试编译cppreference中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)。
这是我做错了什么还是 clang 的 bug?
std::get_if
来模拟std::get
的行为?前者相当冗长 :( - ch271828nget
函数模板。但是它会抛出哪个异常? - Tobi