1

我想实现类,假设有字段键和类 A 或 B。这个类的构造函数中的参数是字符数组。构造函数伪代码将查看第一个字符,如果它与 0x00 不同,它将创建 A 类对象,否则将创建 B 类对象 - 两个类都将字符数组作为参数。

无论如何,我想保持这个实现简单。除非我真的需要,否则我不想使用 boost::Variant,而且我也不想像这样实现一个“变体”类 ,因为我不熟悉模板编程,我认为我的问题可能是以更简单的方式实现。

4

1 回答 1

2

对于 POD 类型,我们有union(但联合不会记住您分配类型,因此也将其单独存储)。这不适用于非 POD 类型。主要原因是因为 C++ 不知道在构造/删除联合时应该创建哪个/删除联合。

但是联合可以用来保存指向实际类型的指针。然后你必须自己关心构建和删除。

你可以创建这样的东西,它包装了这个指针联合并添加了一个方便的接口。详细解释写在评论里:

class EitherAorB {
    // We have to remember what we actually created:
    enum Which {
        A_Type,
        B_Type
    } m_which;

    // We store either a pointer to an A or to a B. Note that this union only
    // stores one pointer which is reused to interpret it as an A*, B* or void*:
    union {
        A *a;
        B *b;
        void *untyped; // Accessing the same pointer without looking at the type
    } m_ptr;

    // Additional stuff you want to store besides A and B
    const char *m_key;

public:
    EitherAorB(const char *key) {
        // Decision: Which type do we want to create?
        m_which = key[0] == 0 ? A_Type : B_Type;
        // Create the type (the cast to void* make the pointer "untyped"):
        m_ptr.untyped = m_which == A_Type ? (void*)new A() : (void*)new B();

        // Store additional stuff
        m_key = key;
    }
    ~EitherAorB() {
        // Since we stored the actual contents outside and point to them,
        // we have to free the memory. For this, we have to care about the
        // type again, so the correct destructor will be chosen. Deleting
        // the untyped pointer won't work here.
        if (m_which == A_Type) delete m_ptr.a;
        if (m_which == B_Type) delete m_ptr.b;
    }

    // These two functions can be used to query which type is stored.
    bool hasA() const {
        return m_which == A_Type;
    }
    bool hasB() const {
        return m_which == B_Type;
    }

    // These two functions can be used to query the pointers to the actual types.
    // I made them return a null pointer if the wrong getter was used.
    A *getA() {
        return m_which == A_Type ? m_ptr.a : 0;
    }
    B *getB() {
        return m_which == B_Type ? m_ptr.b : 0;
    }
}

请注意,如果您复制EitherAorB. 要解决此问题,请禁用复制(通过将复制构造函数和赋值运算符设为私有或在 C++11 中使用 禁用它们= delete),或实现将深度复制指针对象的复制构造函数和赋值运算符。


你说你不熟悉模板编程。使这个实现模板化并不困难。放在template<typename A, typename B>整个类定义之前;然后它应该开箱即用。.cpp但是,在这种情况下不要移动文件中的实现;最好是在我写的时候让它们内联。

然后,A不是B类型,而是您在客户端代码中分配类型的占位符。然后我将 tempalte 类重命名为 just Either,这样你的类型名称就变成了Either<This, That>.

于 2013-05-10T10:34:52.623 回答