我不知道 C++03 中 std::pair 的“错误”是什么,但如果我天真地重新实现它,我没有任何问题,(使用相同的编译器 gcc 和 @987654323 @)。
double a = 1.;
double b = 2.;
my::pair<double, double> p1(5., 6.);
my::pair<double&, double&> p2(a, b);
p2 = p1; // a == 5.
因此,解决方法可能是 (1) 重新实现 pair(在不同的命名空间中),或 (2) 专门用于 std::pair<T&, T&>,或 (3) 简单地使用 C++11(其中 std::pair 用于引用开箱即用)
(1) 这里是简单的实现
namespace my{
template<class T1, class T2>
struct pair{
typedef T1 first_type;
typedef T2 second_type;
T1 first;
T2 second;
pair(T1 const& t1, T2 const& t2) : first(t1), second(t2){}
template<class U1, class U2> pair(pair<U1, U2> const& p) : first(p.first), second(p.second){}
template<class U1, class U2>
pair& operator=(const pair<U1, U2>& p){
first = p.first;
second = p.second;
return *this;
}
};
template<class T1, class T2>
pair<T1, T2> make_pair(T1 t1, T2 t2){
return pair<T1, T2>(t1, t2);
}
}
(2) 这里是 std::pair 的特化(有些人可能会抱怨我在使用 std 命名空间进行重载/特化,但我认为如果它可以扩展类)
namespace std{
template<class T1, class T2>
struct pair<T1&, T2&>{
typedef T1& first_type; /// @c first_type is the first bound type
typedef T2& second_type; /// @c second_type is the second bound type
first_type first;
second_type second;
pair(T1& t1, T2& t2) : first(t1), second(t2){}
template<class U1, class U2> pair(pair<U1, U2> const& p) : first(p.first), second(p.second){}
template<class U1, class U2>
pair& operator=(const pair<U1, U2>& p){
first = p.first;
second = p.second;
return *this;
}
};
}
也许我遗漏了一些明显的东西,如果指出了一些明显的缺陷,我可以编辑答案。