cmo*_*cmo 3 c++ overloading std operator-keyword std-pair
我用很多价值观做了很多工作:std::pair<int, int> my_pair.有时候,我需要在这两个执行相同的操作my_pair.first和my_pair.second.
如果我能做到my_pair[j]并循环 j = 0,1,我的代码会更顺畅.(我正在避免使用数组,因为我不想打扰分配内存,我pair广泛使用其他东西).
因此,我想定义 operator[]的std::pair<int, int>.
我无法让它工作,(我对模板等不太好)...
#include <utility>
#include <stdlib.h>
template <class T1> T1& std::pair<T1, T1>::operator[](const uint &indx) const
{
if (indx == 0)
return first;
else
return second;
};
int main()
{
// ....
return 0;
}
Run Code Online (Sandbox Code Playgroud)
无法编译.其他变化也失败了.
据我所知,我正在关注Stack Overflow运算符重载FAQ,但我想我错过了一些东西......
这是一个非成员实现:
/// @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);
Run Code Online (Sandbox Code Playgroud)
请注意,我们需要两个版本:一个用于只读对,一个用于可变对.
不要害怕大量使用非成员函数.正如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;
});
Run Code Online (Sandbox Code Playgroud)
如果你有C++ 11 lambdas并且至少有点安全,因为它没有可能访问越界,这并不是太难以使用.
| 归档时间: |
|
| 查看次数: |
1561 次 |
| 最近记录: |