假设有类:
struct A { int a; virtual size_t GetMemoryUsage() const { return sizeof(*this); } }; struct B : public A { int b; };
并且可能存在更深层次的继承.
我想要的是有一个方法,它将返回一个对象在内存中占用的字节数,在这种情况下是GetMemoryUsage().通常可以通过使用sizeof(* this)来实现.问题是(至少AFAIU),我必须覆盖每个派生类中的方法,并实际复制粘贴其正文.我不喜欢重复的代码:)
我对么?如何通过仅从基类的方法调用sizeof(* this)和decltype(* this)来返回我想要的子类?有更优雅的解决方案吗?
解决方法
您不必手动为每个派生类实现GetMemoryUsage,只需将其保留为纯虚拟.例如.:
struct A { virtual ~A() = default; virtual size_t GetMemoryUsage() const noexcept = 0; }; struct B : A { int b; };
但是,在创建对象时,必须实现该功能.您可以使用工厂函数来执行此操作,该函数使用该纯虚拟的通用实现“修饰”该类:
// Can alternatively be defined inside function template create. template<class T> struct GetMemoryUsageImpl : T { using T::T; size_t GetMemoryUsage() const noexcept final { return sizeof(T); } }; template<class T,class... Args> std::unique_ptr<T> create(Args&&... args) { return std::unique_ptr<T>(new GetMemoryUsageImpl<T>(std::forward<Args>(args)...)); }
用法:
void f(A& a) { auto object_size = a.GetMemoryUsage(); } int main() { auto b = create<B>(); f(*b); }
You can also implement a hierarchy of interfaces incrementally easily using this idiom.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。