I don't know what is "wrong" with std::pair
in C++03 but if I reimplement it naively, I don't have any problem with it, (using the same compiler gcc
and clang
).
double a = 1.;
double b = 2.;
my::pair<double, double> p1(5., 6.);
my::pair<double&, double&> p2(a, b);
p2 = p1; // a == 5.
So a workaround could be to (1) reimplement pair
(in a different namespace), or (2) specialize for std::pair<T&, T&>
, or (3) simply use C++11 (where std::pair
for refs works out of the box)
(1) Here it is the naive implementation
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) And here it is an specialization of std::pair
(some people may complain that I am messing around overloading/specializing with the std
namespace, but I think it is ok if it is to extend the capabilities of the class)
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;
}
};
}
Maybe I am missing something obvious, I can edit the answer if some obvious flaws, are pointed.
std::pair<A*,B*>
– Systemicboost::ref
s as well. – Longfacedboost::reference_wrapper
is not assignable. – Setscrewstd::pair
of references is valid in C++11 but not in C++03, (not sure if because a change of the semantics of the language or because the standard library has changed.)boost::tuple
is a solution in C++03 but it sounds like and overkill at first glance. – Divulgate