c++ - std::make_pair 自动类型推断?
问题描述
考虑这个函数:
std::pair<int, double> getPair()
{
return std::make_pair(0, 0);
}
为什么会这样编译?
不应该make_pair
返回一个std::pair<int, int>
不兼容的std::pair<int, double>
?从 int 到 double 的转换发生在哪里?
示例代码链接:https ://ideone.com/Zq6ooY
解决方案
std::make_pair(0, 0);
确实创建了一个std::pair<int,int>
对象。但是,您对配对不兼容是不正确的。如果它们的论点是兼容的,它们是兼容的。
请参阅cppreference:
// #4
template< class U1, class U2 >
constexpr std::pair<T1,T2>( const pair<U1, U2>& p );
// #5
template< class U1, class U2 >
constexpr std::pair<T1,T2>( pair<U1, U2>&& p );
TX
如果可以从 types 构造类型,则启用这些UX
,在您的情况下使用 #5,因为int
can beconstructed from double&&
。
推荐阅读
- android - 如何修复 java.lang.NoClassDefFoundError:在 android studio 3.6.1 中解析失败:Lcom/google/android/gms/common/R$string?
- kotlin - WebSocket 握手响应缺少 HTTP 状态行
- haskell - 使用镜头访问字段
- android - 构建调试时不使用 build.gradle 中的部分代码的条件
- google-sheets - FILTER() 与 Google 表格中其他列的完整性问题
- mysql - 为什么我必须在这里使用 group by?
- apache-kafka-connect - 如何配置 Confluent Kafka Connect 本地 S3 接收器
- angular - PWA 不适用于构建版本,仅适用于本地主机上的 prod 构建版本
- python - 有什么方法可以在 Django 中的模型内部进行过滤?
- sql - 从 MS Access DB 表中提取带有条件和分组的数据