在分配给变体时,我觉得我遗漏了一些关于 int 类型提升的明显信息。
在 gcc 9.3.0 版本(Ubuntu 9.3.0-11ubuntu0~18.04.1)上,使用 -std=c++17 编译,以下代码编译失败:
#include <variant>
#include <iostream>
int main()
{
std::variant<long int, bool> v; // works fine if "long" is omitted
long int sanity = 1; // verify that we can assign 1 to a long int; works fine
std::cout << sizeof(sanity) << "\n";
v = 1; // compiler error here: why doesn't this assign to the long int variant of v?
return 0;
}
Run Code Online (Sandbox Code Playgroud)
错误信息:
error: no match for ‘operator=’ (operand types …Run Code Online (Sandbox Code Playgroud)