比方說,我有以下結構:模板多態性派生類的大小沒有新成員
template <typename T>
struct Wrapper {
virtual T* get() const = 0;
protected:
void *c_;
};
template <typename C, typename T>
struct WrapperOf: Wrapper<T> {
WrapperOf(C *c = 0) : c_(c) { }
virtual T* get() const {
C *c = static_cast<C*>(c_);
return static_cast<T*>(c->get());
}
};
它是由標準的保證,任何WrapperOf
的大小將是相同的?通常情況下,我可以做到以下幾點:
struct Dummy { void* get(); };
struct Real { int* get(); };
char storage[sizeof(WrapperOf<Dummy, void>)];
Wrapper<int> *wp =
new(storage) WrapperOf<Real, int>();
如果我專注WrapperOf
,通常爲:
template <>
struct WrapperOf<void, void>: Wrapper<void> {
virtual void* get() const { return 0; }
};
用它來初始化存儲(以避免一個Dummy
類):
char storage[sizeof(WrapperOf<void, void>)];
這仍然有效嗎?
所以你問如果sizeof(WrapperOf )== sizeof(WrapperOf)'? –
NathanOliver
@NathanOliver以及與'char []'相同的對齊方式...... –
@NathanOliver是,正好 - 或者至少如果sizeof(WrapperOf )== sizeof(WrapperOf )''。 – Holt