我可以使用std :: pair,但重命名.first和.second成员名称吗? [英] Can I use std::pair, but rename .first and .second member names?

查看:138
本文介绍了我可以使用std :: pair,但重命名.first和.second成员名称吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的一个常见设计问题是,我将两个变量捆绑在一起,然后失去了以有意义的方式引用它们的能力。

A common design problem I run into, is that I bundle two variables together and then lose the ability to reference them in a meaningful way.

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

I've considered writing basic structs instead, but then I lose a lot of the benefits that come along with std::pair:


  • make_pair

  • 非成员重载运算符

  • 交换

  • 获取

  • 等。

  • make_pair
  • non-member overloaded operators
  • swap
  • get
  • etc.

是否可以重命名或提供 first 第二个数据成员?

Is there a way to rename or provide an alternative identifier for the first and second data members?

我希望利用所有接受<$ c的功能$ c> std :: pair ,

,但仍然可以通过以下方式使用它们:

I was hoping to leverage all of the the functions that accept std::pair,
but still be able to use them in the following way:

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);


推荐答案

解决这个问题的一种方法是使用< a href = http://en.cppreference.com/w/cpp/utility/tuple/tie rel = noreferrer> std :: tie 。您可以 tie()返回已命名的变量,以便使用好名字。

One way you could get around this is to use std::tie. You can tie() the return into variables that you have named so that you have good names.

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()也可以使用该功能。

Another benefit with this is if you ever change the function to return a tuple tie() will also work with that.

使用C ++ 17,我们现在有了结构化绑定,它允许您声明多个变量并将其绑定到函数的返回。这适用于数组,类似对象的元组/对和结构/类(只要它们满足某些要求)。在这种情况下使用结构化绑定,可以将上面的示例转换为

With C++17 we now have structured bindings which allow you to declare and bind multiple variables to the return of the function. This work with arrays, tuple/pair like objects and struct/classes (as long as they meet some requirments). Using structured bindings in this case lets use convert the above example into

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 的引用

and now x_pos is a reference to cords.first and y_pos is a reference to cords.second.

这篇关于我可以使用std :: pair,但重命名.first和.second成员名称吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆