添加 std::pair 与 + 运算符 [英] Add std::pair with + operator

查看:32
本文介绍了添加 std::pair 与 + 运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种简单的方法可以让 a+b 在下面的例子中工作:

Is there a simple way to make a+b work in the following example:

#include <utility>
#include <iostream>

int main ()
{
    std::pair<int, int> a=std::make_pair(1,2);
    std::pair<int, int> b=std::make_pair(3,3);
    std::pair<int, int> c = a+b;

    return 0;
}

推荐答案

template <typename T,typename U>                                                   
std::pair<T,U> operator+(const std::pair<T,U> & l,const std::pair<T,U> & r) {   
    return {l.first+r.first,l.second+r.second};                                    
}                                                                                  
int main ()                                                                        
{                                                                                  
    std::pair<int, int> a=std::make_pair(1,2);                                     
    std::pair<int, int> b=std::make_pair(3,3);                                     
    std::pair<int, int> c = a+b;                                                   

    return 0;                                                                      
}  

您还可以使用更多模板类型来执行此操作,以支持添加两种不同的类型.现在它支持添加第一个和第二个是不同类型的对,但两个对和返回必须具有相同的类型.

You can also do this with more template types to support adding two different types. Right now it supports adding pairs where the first and second are different types, but the two pairs and the return must have the same type.

如果你想让这个函数真正通用,你可以这样做

If you want to make the function really versatile you could do this

template <typename T,typename U, typename V,typename W>                            
auto operator+(const std::pair<T,U> & l,const std::pair<V,W> & r)                  
-> std::pair<decltype(l.first+r.first),decltype(l.second+r.second)>                
{                                                                                  
    return {l.first+r.first,l.second+r.second};                                    
} 

在 c++14 中,如果您显式返回一对,您可能可以使用 auto 而不是尾随返回类型.

In c++14 you might be able to get away with auto instead of the trailing return type, if you explicitly return a pair.

这篇关于添加 std::pair 与 + 运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆