我遇到的一个常见设计问题是,我将两个变量捆绑在一起,然后失去以有意义的方式引用它们的能力。
std::pair<int,int> cords;
cord.first = 0; //is .first the x or y coordinate?
cord.second = 0; //is .second the x or y coordinate?
我考虑过编写基本结构,但是我失去了很多 std::pair
:
- make_pair
- 非成员重载运算符
- 交换
- 得到
- 等等
有没有办法为 first
和 second
数据成员重命名或提供替代标识符?
我希望利用所有接受 std::pair
的函数,
但仍然可以通过以下方式使用它们:
std::pair<int,int> cords;
//special magic to get an alternative name of access for each data member.
//.first and .second each have an alternative name.
cords.x = 1;
assert(cords.x == cords.first);
最佳答案
解决此问题的一种方法是使用 std::tie
.你可以tie()
返回你已经命名的变量,这样你就有了好名字。
int x_pos, y_pos;
std::tie(x_pos, y_pos) = function_that_returns_pair_of_cords();
// now we can use x_pos and y_pos instead of pair_name.first and pair_name.second
这样做的另一个好处是,如果您将函数更改为返回元组 tie()
也可以使用它。
使用 C++17 我们现在有 structured bindings它允许您声明多个变量并将其绑定(bind)到函数的返回。这适用于数组、元组/配对对象和结构/类(只要它们满足一些要求)。在这种情况下使用结构化绑定(bind)可以将上面的示例转换为
auto [x_pos, y_pos] = function_that_returns_pair_of_cords();
你也可以这样做
auto& [x_pos, y_pos] = cords;
现在 x_pos
是对 cords.first
的引用,而 y_pos
是对 cords.second
的引用.
关于c++ - 我可以使用 std::pair,但重命名 .first 和 .second 成员名称吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32590764/