Vio*_*ffe 7 c++ enums overloading c++17
此代码以MSVC编译器(v141工具集,/ std:c ++ 17)的意外方式运行:
#include <iostream>
#include <limits>
#include <sstream>
#include <stdint.h>
int main() {
std::ostringstream ss;
enum Enum : int64_t {muchos_digitos = std::numeric_limits<int64_t>::max() - 1000};
ss << muchos_digitos;
std::cout << ss.str();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
具体来说,它打印"-1001".只有经过多次头部刮擦和启用/W4警告级别后才发现原因:
警告C4305:'参数':从'main :: Enum'截断到'int'
但为什么会这样呢?实际上,调试器确认int调用了重载而不是long long,但为什么呢?我怎样才能在通用代码中规避这一点?我投muchos_digitos来int64_t,但我收到的价值typename T.我可以弄清楚它是一个枚举,但我怎么知道它是一个强类型的枚举,我能找到它的基础类型吗?我不认为这是直接可能的......
GCC下的输出是正确的,但我需要代码才能与GCC,clang和MSVC三个一起使用.
PS首先没有为我的项目设置/ W4是一个错误.我建议大家在MSVC和-pedantic-errorsGCC/clang中使用这个级别,当你在编写代码时在编译时注意到它时,它确实可以节省你的时间和bizzare错误以及令人惊讶的行为.
Microsoft 团队确认这是一个错误,现已在 VS 2019 中修复:https://developercommunity.visualstudio.com/content/problem/475488/wrong-ostringstreamoperator-overload-selected-for.html