考虑这个函数:
std::pair<int, double> getPair()
{
return std::make_pair(0, 0);
}
为什么这段代码能够编译通过?
make_pair
不应该返回一个类型为 std::pair<int, int>
的值吗?它与类型为 std::pair<int, double>
的实参不兼容,那么从整型到双精度浮点数的转换在哪里发生了呢?
示例代码链接: https://ideone.com/Zq6ooY
考虑这个函数:
std::pair<int, double> getPair()
{
return std::make_pair(0, 0);
}
为什么这段代码能够编译通过?
make_pair
不应该返回一个类型为 std::pair<int, int>
的值吗?它与类型为 std::pair<int, double>
的实参不兼容,那么从整型到双精度浮点数的转换在哪里发生了呢?
示例代码链接: https://ideone.com/Zq6ooY
std::make_pair(0, 0);
确实创建了一个std::pair<int,int>
对象。但是,如果它们的参数兼容,则你关于pair不兼容是错误的。
请参见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&&
构建。