隐式类型转换
#include <iostream>
#include <variant>
#include <string>
int main() {
auto const v = std::variant<bool, std::string>{"hello"};
std::cout << v.index() << '\n'; // prints 0
}
因为"hello"
是char const*
,而char const*
可以被隐式转换成bool
,所以variant
的实际类型是bool
而不是std::string
类不说,基本的数学运算,C/C++也做不好
#include <iostream>
int main() {
int a = -1;
unsigned b = 1;
if (a > b) {
std::cout << "-1 > 1\n";
}
}
它打印-1 > 1
,因为a
与b
的宽度一致,此时无符号数的优先级更高,a
被根据numeric conversions规则转成了无符号数即232-1,当然大于b
而
#include <iostream>
void foo(int) { std::cout << "int\n"; }
void foo(unsigned) { std::cout << "unsigned\n"; }
int main() {
foo(uint8_t{3});
}
调用的是foo(unsigned)
,这里uint8_t{3}
被根据 integral promotion 规则提升成了unsigned
类型
WTF