c++ - std::is_convertible 何时考虑原始类型可转换?

标签 c++ primitive-types

使用 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, if std::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/

相关文章:

java - 原始类型只是不从 java.lang.Object 继承的类型吗?

garbage-collection - Kotlin 的 Float、Int 等是否针对 JVM 中的内置类型进行了优化?

c++ - 在动态分配的内存上调用 memset 会导致堆损坏吗

c++ - 预定义大小的静态数组中的元素数

c++ - 有效地从 unordered_set 中删除 unique_ptr

java - Java 中的字符串和字符数组

c - 尝试打印一个无符号长整数,但得到一个不同的数字

c++ - 在可变参数模板函数中连接字符串(和数字)

c++ - Linux 中 <conio.h> 的替换

java - 是否可以在 java 中定义与基元一起使用的自定义类型?