c++ - 在基类中有一个方法可以分配给子类

标签 c++ c++11 shared-ptr

我正在尝试拥有一个公共(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/

相关文章:

c++ - 为什么函数不能正确地转换指针(从基类到派生类)

c++ - 防止在 main 之后 self 破坏?

c++ - 无法使用Xcode通过boost成功编译

c++ - 如何使用 juce 的 FileFilter 描述我想要的文件过滤器?

c++ - CRTP 模式和 enable_shared_from_this

c++ - 在到达范围结束后 boost 共享指针 "runtime error"

c++ - 安排这门课的最佳方式是什么?

c++ - 创建线程时编译器错误

c++ - 为什么需要一个空的 shared_ptr 以及如何使用它?

c++ - 使用 C++11 类型特征提供替代的内联实现