#include<iostream> using namespace std; template<typename CustomClass> class Optimizable{ private: CustomClass info; void* storage; }; class Test{ }; int main() { cout << sizeof(Optimizable<Test>) << endl; //结果为8 return 0; }
优化后:
#include<iostream> using namespace std; template<typename Base, typename Member> class BaseMemberPair : private Base{ private: Member member; public: BaseMemberPair(Base const &b, Member const &m):Base(b), member(m){} //通过first来访问基类数据 Base const& first() const{ return (Base const&)*this; } //提供给const对象调用 Base& first() { return (Base&)*this; } //通过second()来访问成员变量 Member const& second() const { return this->member; } Member& second() { return this->member; } }; template <typename CustomClass> class Optimizable { private: BaseMemberPair<CustomClass, void*> info_and_storage; }; class Test{ }; int main() { cout << sizeof(Optimizable<Test>) << endl; //结果为4 return 0; }
5、警告:
原文:http://www.cnblogs.com/claruarius/p/4111581.html