使用 std::is_convertible :
bool i2c = std::is_convertible<int, char>::value;
bool c2i = std::is_convertible<char, int>::value;
bool f2i = std::is_convertible<float, int>::value;
std::cout << std::boolalpha;
std::cout << i2c << '\n'; //prints true
std::cout << c2i << '\n'; //prints true
std::cout << f2i << '\n'; //prints true
我不明白为什么上述所有情况的输出都必须是 true
,当它们看起来是不可转换的(类型转换可能导致精度损失).或者我们不应该使用 std::is_convertible
来比较原始类型?
最佳答案
页面链接状态:
If the return statement in the imaginary function definition
{ return std::declval<From>(); }
is well-formed, (that is, ifstd::declval<From>()
can be converted using implicit conversion), provides the member constant value equal to true.
所有提到的类型都可以隐式转换(尽管编译器可能会发出警告),即:
float f = 0.8f
int i = f; // Legal implicit conversion.
完全合法且格式正确。所以std::is_convertible<float, int>::value
将是真实的。这同样适用于列出的比较的其余部分。
关于c++ - std::is_convertible 何时考虑原始类型可转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41289938/