我正在尝试拥有一个公共(public)基类/辅助类,为调用类分配 shared_ptr,但我在派生类中使用它时遇到了问题。
#include <memory>
template<typename T>
struct SPAlloc {
virtual ~SPAlloc() {}
template<typename ...Args>
static std::shared_ptr<T>
Alloc(Args&&... params) {
return std::make_shared<T>(std::forward<Args>(params)...);
}
template<class U, typename ...Args>
static std::shared_ptr<U>
Alloc(Args&&... params) {
return std::make_shared<U>(std::forward<Args>(params)...);
}
};
class Base : public SPAlloc<Base> {
public:
virtual ~Base() {};
};
class Child : public Base {
public:
virtual ~Child() {};
};
typedef std::shared_ptr<Base> pBase;
typedef std::shared_ptr<Child> pChild;
int main() {
pBase base = Base::Alloc();
pChild child = Child::Alloc();
}
据我所知,class Base : public SPAlloc<Base>
意味着 T
在模板中将是 Base
,这就是我创建第二个 Alloc 的原因。第二个分配需要像 Child::Alloc<Child>()
一样调用.
有没有办法写这个Alloc
以便编译器可以推断出我正在调用 Alloc 的类?
最佳答案
简短回答:不,没有。
长答案:关键是 Alloc
不知道Child
除非明确告知,否则这些信息从何而来?调用Child::Alloc()
是对 Base::Alloc()
的调用,这是对 SPAlloc<Base>::Alloc()
的调用在那里,关于 Child
的所有信息丢失了。
最简单的解决方案是使用一个免费函数,但该函数已经存在并且名为:std::make_shared
.也许考虑直接使用它并避免使用 SPAlloc
的麻烦完全。
或者,如果你想覆盖 SPAlloc<T>::Alloc()
对于每个 child ,您不需要基类 SPAlloc
根本上,只需将方法添加到每个类,这可能比使用基类更容易。
关于c++ - 在基类中有一个方法可以分配给子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15605223/