【发布时间】:2012-03-19 03:22:33
【问题描述】:
我有一堆属性,可以是 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<ATag>只有在ATag = AttributeTag时才会有大小。其余案例将仅为空类。这个100号码也是从哪里来的?我看不出有什么问题。请把你的问题说清楚。 -
100只是为了夸大问题。
标签: c++ templates metaprogramming