'How to alias pair member-data in C++?
How to alias pair member-data in C++ ?
I have a container of std::pair<int,int> to store master-slave pairs.
For better readability I want to use something like:
using Master = std::pair<int,int>::first;
std::pair<int,int> myPair;
auto myMaster = myPair.Master;
What would be the correct syntax here?
Thank you, in advance.
Solution 1:[1]
An alternative would be to use the tuple-like get access to std::pair with a self-defined constant:
const std::size_t Master = 0;
std::pair<int,int> myPair;
auto myMaster = std::get< Master >( myPair );
Somewhat cleaner and more readable than pointered access IMHO.
Solution 2:[2]
You can name a pointer-to-member
constexpr auto Master = &std::pair<int,int>::first;
std::pair<int,int> myPair;
auto myMaster = myPair.*Master;
Solution 3:[3]
I am going with the following:
int main() {
cout<<"Hello World\n";
constexpr auto Master = &std::pair<int,int>::first;
std::pair<int,int> myPair;
std::pair<int,int> myPair2;
myPair.*Master = 321;
myPair2.*Master = 10;
cout<<myPair.*Master;
cout<<myPair2.*Master;
return 0;
}
Thanks @Caleth
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | DevSolar |
| Solution 2 | Caleth |
| Solution 3 | Supreeto |
