20

私が遭遇する一般的な設計上の問題は、2 つの変数を一緒にバンドルすると、それらを意味のある方法で参照できなくなることです。

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

5 に答える 5

6

無料の関数を作ることができます:

int& get_x(std::pair<int, int>& p) { return p.first; }
int& get_y(std::pair<int, int>& p) { return p.second; }
int const& get_x(std::pair<int, int> const& p) { return p.first; }
int const& get_y(std::pair<int, int> const& p) { return p.second; }
于 2015-09-15T16:28:31.717 に答える