考虑这个函数:
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
,这些将被启用可以从类型 UX
构造,在您的情况下,使用 #5 是因为 int
可以从 double&&
构建.
关于c++ - std::make_pair 自动类型推导?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64116637/