我觉得在给变量赋值时,整型类型提升方面有一些很容易被忽略的细节。
使用gcc版本为9.3.0(Ubuntu 9.3.0-11ubuntu0~18.04.1)并使用-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’)
有没有什么魔法可以让这个工作按预期进行,而不需要在赋值时进行显式转换?谢谢!