我在使用 std::variant 编译代码时遇到问题。我尝试使用 g++ 5.4/6.2 在 ubuntu 和 fedora 上使用 -std=c++17 编译此代码:
#include <variant>
#include <string>
int main()
{
std::variant<int, float> v, w;
v = 12; // v contains int
int i = std::get<int>(v);
w = std::get<int>(v);
w = std::get<0>(v); // same effect as the previous line
w = v; // same effect as the previous line
try {
std::get<float>(w); // w contains int, not float: will throw
}
catch (std::bad_variant_access&) {}
std::variant<std::string> v("abc"); // converting constructors work when unambiguous
v = "def"; // converting assignment also works when unambiguous
}
Run Code Online (Sandbox Code Playgroud)
在 cppreference.com 上找到,但此错误附加:“致命错误:变体:没有此类文件或目录”。
小智 6
sudo add-apt-repository ppa:ubuntu-toolchain-r/test -y
sudo apt-get update
sudo apt-get install g++-7
跑 /usr/bin/g++-7 -std=c++1z your_program.cc
可选,如果您使用cmake系统,请添加以下行:
set(CMAKE_CXX_COMPILER "/usr/bin/g++-7")
set(CMAKE_CXX_FLAGS "-std=c++1z")