Aragon
Aragon

Reputation: 1551

How can I keep 'first' and 'second' replacing std::pair with struct?

I have a pair std::pair<int, long> and in code at various places use pr.first, pr.second (also ppr->first, ppr->second) kind of notations. Now I want to change the pair to a struct,

struct ABC 
{
    int a;
    long b;
};

is there a way I can keep these 'first' and 'second' notations in code to access this struct? Maybe creating a function?

Upvotes: 2

Views: 857

Answers (2)

Bathsheba
Bathsheba

Reputation: 234665

Setting aside the reasons for your wanting to do this (which in the absence of any other information seem to be questionable to say the least), the simplest way would be to use

struct ABC
{
    int first;
    long second;
};

But if you want the members to be called something else and you don't want to resort to "getter" functions (which would require parentheses at the calling site), a solution is to use references for the member variables:

struct ABC {
    int a;
    long b;

    int& first;
    long& second;

    ABC() : first(a), second(b) {}
};

But if you adopt this you need to write the constructors that are part of the "rule of 5" yourself to bind the references correctly, otherwise a seemingly anodyne copy or move will not work.

Although this answer showcases the power of C++, the language is famed for its ability in allowing you to shoot yourself in the foot. Fancy as the solution may well be, the potential for curious bugs to be introduced as your codebase and even the language itself evolve cannot be overstated. As such this ought to be considered to be an antipattern and only used in truly exceptional circumstances.

Upvotes: 3

Reinhold
Reinhold

Reputation: 584

You may want to try this:

struct ABC 
{
    union {
        int a;
        int first;
    };
    union {
        long b;
        long second;
    };
};

This allows you to use a and first as well as b and second interchangable. It might be better though to replace the firstand second usages to avoid confusion.

As pointed out this is undefined behaviour 12.3 Unions but will work with MSVC and GCC at least. thx for the comments

Upvotes: 2

Related Questions