您好,登录后才能下订单哦!
这篇文章主要介绍“C++中怎么使用匿名联合体实现附带标签的联合体”,在日常操作中,相信很多人在C++中怎么使用匿名联合体实现附带标签的联合体问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”C++中怎么使用匿名联合体实现附带标签的联合体”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
A well-designed tagged union is type safe. An anonymous union simplifies the definition of a class with a (tag, union) pair.
良好设计的命名联合体是类型安全的。无名联合体简化了包含(标签,联合体)对的类的设计。
Example(示例)
This example is mostly borrowed from TC++PL4 pp216-218. You can look there for an explanation.
这段示例代码主要借用自TC++PL4的216页到218页(中文版:C++程序设计语言(原书第四版)p186-p188)。你可以查看该书中的解释。
The code is somewhat elaborate. Handling a type with user-defined assignment and destructor is tricky. Saving programmers from having to write such code is one reason for including variant in the standard.
这段代码有些复杂。使用用户定义的赋值和析构函数处理一种类型不是那么容易。把程序员从必须编写这样的代码的情况中解救出来是在标准库中增加variant的原因之一。
class Value { // two alternative representations represented as a union
private:
    enum class Tag { number, text };
    Tag type; // discriminant
    union { // representation (note: anonymous union)
        int i;
        string s; // string has default constructor, copy operations, and destructor
    };
public:
    struct Bad_entry { }; // used for exceptions
    ~Value();
    Value& operator=(const Value&);   // necessary because of the string variant
    Value(const Value&);
    // ...
    int number() const;
    string text() const;
    void set_number(int n);
    void set_text(const string&);
    // ...
};
int Value::number() const
{
    if (type != Tag::number) throw Bad_entry{};
    return i;
}
string Value::text() const
{
    if (type != Tag::text) throw Bad_entry{};
    return s;
}
void Value::set_number(int n)
{
    if (type == Tag::text) {
        s.~string();      // explicitly destroy string
        type = Tag::number;
    }
    i = n;
}
void Value::set_text(const string& ss)
{
    if (type == Tag::text)
        s = ss;
    else {
        new(&s) string{ss};   // placement new: explicitly construct string
        type = Tag::text;
    }
}
Value& Value::operator=(const Value& e)   // necessary because of the string variant
{
    if (type == Tag::text && e.type == Tag::text) {
        s = e.s;    // usual string assignment
        return *this;
    }
    if (type == Tag::text) s.~string(); // explicit destroy
    switch (e.type) {
    case Tag::number:
        i = e.i;
        break;
    case Tag::text:
        new(&s) string(e.s);   // placement new: explicit construct
    }
    type = e.type;
    return *this;
}
Value::~Value()
{
    if (type == Tag::text) s.~string(); // explicit destroy
}到此,关于“C++中怎么使用匿名联合体实现附带标签的联合体”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。