如何保持'first'和'second'用struct替换std :: pair?

问题描述 投票:2回答:2

我有一对std::pair<int, long>和代码在不同的地方使用pr.firstpr.second(也ppr->firstppr->second)的一种符号。现在我想将对更改为结构,

struct ABC 
{
    int a;
    long b;
};

有没有办法在代码中保留这些“第一”和“第二”符号来访问这个结构?也许创造一个功能?

c++ struct std-pair
2个回答
3
投票

撇开你想要这样做的原因(在没有任何其他信息的情况下,至少可以说是有问题的),最简单的方法是使用

struct ABC
{
    int first;
    long second;
};

但是如果你想要成员被调用其他东西并且你不想求助于“getter”函数(这需要在调用站点使用括号),解决方案是使用成员变量的引用:

struct ABC {
    int a;
    long b;

    int& first;
    long& second;

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

但是如果你采用这个,你需要自己编写属于“5规则”的构造函数来正确绑定引用,否则看似无效的副本或移动将无效。

虽然这个答案展示了C ++的强大功能,但这种语言因其能够让你自己拍摄自己的能力而闻名。很有可能,因为您的代码库甚至语言本身的发展都可能引发奇怪的错误,这一点不容小觑。因此,这应该被认为是反模式,仅用于真正特殊情况。


2
投票

你可能想试试这个:

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

这允许你使用afirst以及bsecond interchangable。虽然更换firstand second用法以避免混淆可能会更好。

正如指出这是undefined behaviour 12.3 Unions,但至少可以与MSVC和GCC合作。 thx的评论

© www.soinside.com 2019 - 2024. All rights reserved.