在分配给变体时,我觉得我缺少一些关于 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;
}
错误信息:
error: no match for ‘operator=’ (operand types are ‘std::variant<long int, bool>’ and ‘int’)
是否有任何魔法可以让这项工作按预期进行,而不需要在作业中进行显式转换?谢谢!