首页 > 解决方案 > 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

标签: c++

解决方案


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,因为intcan beconstructed from double&&


推荐阅读