gpt4 book ai didi

c++ - 如何减少大量包装类的实现代码?

转载 作者:行者123 更新时间:2023-12-02 02:50:56 26 4
gpt4 key购买 nike

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

经过一番讨论,我发现将共享指针返回给库用户并不是一个好主意,因为在这种情况下我无法确保可以在我的库内存中精确地删除该对象。返回弱指针也有同样的问题,因为如果 API .lock() 的用户是弱指针并将结果共享指针保留在某处,我将再次面临同样的问题。

我的最终想法是为弱指针公开某种包装器。包装类可以是这样的:

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
};

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

最佳答案

如果您在包装器中删除继承,您可以执行如下操作来分解所有包装器:

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.");
}
}
};

关于c++ - 如何减少大量包装类的实现代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58518574/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com