如何减少很多包装类的实现代码? [英] How to reduce the implementation code of lots of wrapper classes?

查看:115
本文介绍了如何减少很多包装类的实现代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发带有一些类的库,我们称它们为C1, C2 and ... Cn.这些类中的每一个都实现一些接口,即I1, I2, ... Im.(n> m).库中对象之间的关系很复杂,我必须 提供一些API,供我的图书馆用户使用智能指针访问这些对象.

I am developing a library with some classes, let's call them C1, C2 and ... Cn. Each of these classes realize some interfaces, i.e. I1, I2, ... Im. (n > m). The relationship between objects in the library is complex and I have to provide some API for my library users to access these objects using smart pointers.

经过一些讨论,我发现将共享指针返回给库用户不是一个好主意,因为在那种情况下,我不能确保可以在我的库的内存中精确地删除该对象.返回弱指针有相同的问题,因为如果API .lock()的用户使用弱指针并将结果共享指针放在某个地方,我将再次遇到相同的问题.

After some discussions, I found that returning shared pointers to the library users is not a good idea, because in that case I cannot make sure that the object can be removed precisely in my library's memory. Returning weak pointers have the same issue, because if the user of the API .lock()s the weak pointer and keep the resulted shared pointer somewhere, I will face the same problem again.

我最后的想法是为弱指针提供某种包装.包装器类可以是这样的:

The final idea I have, is to expose some kind of wrappers for the weak pointers. A wrapper class can be something like this:

class Wrapper_C1 : public I1
{
   std::weak_ptr<C1> mC1;
public:
   Wrapper_C1() = delete;
   Wrapper_C1(const std::weak_ptr<C1> & c1) : mC1(c1)
   {
   }

   int method1_C1(int x)
   {
       if (auto sp = mC1.lock())
       {
           sp->method1_C1(x);
       }
       else
       {
            throw std::runtime_error("object C1 is not loaded in the lib.");
       }
   }

   void method2_C1(double y)
   {
       if (auto sp = mC1.lock())
       {
           sp->method2_C1(y);
       }
       else
       {
            throw std::runtime_error("object C1 is not loaded in the lib.");
       }
   }

   // The same for other methods
};

如您所见,所有这些包装器类都共享相同的实现.减少所有这些包装器类的代码的最佳方法是什么?无论如何要避免重复类似的代码?

As you see, all of this wrapper classes, share the same implementation. What is the best way to reduce the code of ALL of these wrapper classes? Is there anyway to avoid repeating the similar codes?

推荐答案

如果在包装器中放弃继承,则可以执行以下操作来分解所有包装器:

If you drop inheritance in the wrapper, you might do something like the following to factorize all wrappers:

template <typename T>
class Wrapper
{
private:
   std::weak_ptr<T> m;
public:
   Wrapper() = delete;
   Wrapper(const std::weak_ptr<T> & w) : m(w) {}

   auto operator -> () /* const */
   {
       if (auto sp = m.lock())
       {
           return sp;
       }
       else
       {
            throw std::runtime_error("object is not loaded in the lib.");
       }
   }
};

这篇关于如何减少很多包装类的实现代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆