C++ 是否可以定义从 pair<int, int> 到 pair<float,float> 的隐式转换?

C++ Is it possible to define a implicit conversion from pair<int, int> to pair<float,float>?

template<typename type>
using point = std::pair<type, type>;

template<typename type>
point<type> operator-(point<type> a, point<type> b)
{
    return{ a.first - b.first, a.second - b.second };
}

int main() {
    point<float> a = { 0, 0 };
    point<int> b = { 1, 2 };
    point<float> p = a - b; // This does not compile.       
    return 0;
}

如何将点浮点数和点整数参数传递给我的“-”运算符,并将点整数参数隐式转换为点浮点类型?

当然,我可以将点声明为 class ,并使用构造函数来实现。但这对我来说似乎很冗长。

注: 原来问题没有提到operator-,只是问是否可以自动将point<int>转换为point<float> 而不是 class。我的回答解决了这个问题。我会留作参考。 Colin Pitrat 的回答解决了问题,因为它目前的表述更好。


已经为你定义好了:std::pair有一个广义复制构造函数(即允许可转换模板参数之间隐式转换的构造函数)

template< class U1, class U2 >
pair( const pair<U1, U2>& p );

(在 C++14 中是 constexpr)它允许用 pair<T2, U2> 初始化 pair<T1, U1> 只要 T2 可以隐式转换为 T1U2U1:

4) Initializes first with p.first and second with p.second. (source)

这意味着以下代码运行良好:

template<typename type> 
using point = std::pair<type, type>;

float dist(point<float> a, point<float> b)
{
    return pow(pow(a.first-b.first, 2) + pow(a.second - b.second, 2), 0.5);
}

int main() {
    std::cout << dist(point<int>{ 0, 0 }, point<int>{ 1, 1 });
    return 0;
}