- 您不能将 operator[] 重载为非成员
- 您不能定义尚未在类定义中声明的成员函数
- 您不能修改 std::pair 的类定义
这是一个非成员实现:
/// @return the nth element in the pair. n must be 0 or 1.
template <class T>
const T& pair_at(const std::pair<T, T>& p, unsigned int n)
{
assert(n == 0 || n == 1 && "Pair index must be 0 or 1!");
return n == 0 ? p.first: p.second;
}
/// @return the nth element in the pair. n must be 0 or 1.
template <class T>
T& pair_at(std::pair<T, T>& p, unsigned int index)
{
assert(index == 0 || index == 1 && "Pair index must be 0 or 1!");
return index == 0 ? p.first: p.second;
}
// usage:
pair<int, int> my_pair(1, 2);
for (int j=0; j < 2; ++j)
++pair_at(my_pair, j);
请注意,我们需要两个版本:一个用于只读对,一个用于可变对。
不要害怕自由地使用非成员函数。正如 Stroustrup 自己所说,没有必要用一个对象来建模一切,也没有必要通过继承来增加一切。如果您确实想使用类,请选择组合而不是继承。
你也可以这样做:
/// Applies func to p.first and p.second.
template <class T, class Func>
void for_each_pair(const std::pair<T, T>& p, Func func)
{
func(p.first);
func(p.second);
}
/// Applies func to p.first and p.second.
template <class T, class Func>
void for_each_pair(std::pair<T, T>& p, Func func)
{
func(p.first);
func(p.second);
}
// usage:
pair<int, int> my_pair(1, 2);
for_each_pair(my_pair, [&](int& x){
++x;
});
如果您有 C++11 lambda,那么使用它并不会太笨拙,并且至少更安全一些,因为它没有可能越界访问。