我有一堆可以是NOP或具有状态的属性。对它们的要求是,当用户不需要该属性但仍包含某些方法时,它们的大小不能为任何大小。一个例子:

struct AttributeATag {};

/* The template used when AttributeATag is not specified */
template <typename T>
class AttributeA
{
public:
    void foo(uint32_t v)
    {
        // Nop, do nothing
    }

    enum
    {
        HasAttributeA = false
    };
};

/* The template specialization used when AttributeATag is specified */
template <>
class AttributeA<AttributeATag>
{
public:
    void foo(uint32_t v)
    {
        this->omgVariable = v;
    }

    enum
    {
        HasAttributeA = true
    };
protected:
    int omgVariable;
};

template <typename ATag>
class MyUberClass : public AttributeA<ATag>
{
    // This class now has omgVariable or not, depending on ATag and it
    // has either a NOP method or one which actually does something
    void doSomething()
    {
        if (AttributeA<ATag>::HasAttributeA)
        {
            /* ... */
        }
    }
};


这行得通,但是现在出现了一个问题:NOP属性的大小(为空类时)不为0,这意味着100个空属性会为MyUberClass添加大量未使用的空间。

有没有办法避免这种情况并根据模板参数添加/删除成员变量?



编辑:

据我所知,空类的大小不为0。当我尝试以下内容时,我得到sizeof(B)== 4。

template <typename T>
class A
{

};

class B : public A<int>, public A<double>, public A<char>, public A<long>, public A<bool>
{

};

最佳答案

由于您将AttributeA用作基类,因此几乎每个编译器都将使用“空基优化”来确保空基类在子类中不使用空间,即使基类的大小为非零。我认为您在这里没有问题。

每个类(基类/子类)必须占用至少一个字节(如果编译器填充所有内容,则可能需要四个字节),但是空基数(几乎在每种情况下)都不会增加子类的大小。 。

关于c++ - 在编译时组成成员,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9764610/

10-11 22:47
查看更多