c++模板包含使用相同类型T的对象

c++ template containing object using same type T

本文关键字:同类型 对象 包含使 c++      更新时间:2023-10-16

我有一个类MemoryPool,代码如下:

namespace System
{
    template <class T>
    class MemoryPool
    {
    public:
        // only constructor
        MemoryPool(const size_t itemsToInitNow, const size_t maxItems)
            : _maxItemsInMemoryPool(maxItems)
        {
            // initialize itemsToInitNow items immediately
            for(size_t i = 0; i < itemsToInitNow; ++i) {
                _container.push_back(MemoryItemSharedPointer(new MemoryItem<T>(_factory.CreateItem())));
            }
        }
            .. other stuff
    private:
            .. other stuff
        // private data members
        AbstractFactory<T> _factory;

当我在代码的其他地方实例化对象的实例时,例如

new System::MemoryPool<ParticleShape>(10, 100);
我得到以下编译错误:

System::AbstractFactory<T>::CreateItem(void)无法推导出'T'的模板参数。

我的AbstractFactory类也是一个模板类,我将_factory定义为类型为t的MemoryPool的私有组合对象。我希望每当我实例化一个类型为t的MemoryPool对象时,它将初始化类型为int的组合_factory。

有办法做到这一点吗?

编辑:这是CreateItem方法,在它的初级阶段:

 template <typename T>
 inline const std::shared_ptr<T> CreateItem()
 {
      return std::shared_ptr<T>(new T);
 }

您已经删去了大量代码,但据猜测,您有如下内容:

template<typename T>
class AbstractFactory {
// ......
    template <typename T>
    inline const std::shared_ptr<T> CreateItem()
    {
        return std::shared_ptr<T>(new T);
    }
};

内部模板隐藏了T的外部值-要调用它,您必须这样做:

AbstractFactory<Anything> factory;
std::shared_ptr<int> pInt = factory.CreateItem<int>();

可以看到,内部函数有一个完全独立于外部类的模板形参。您可能只想从内部函数中删除模板参数,因此它采用外部类的模板参数。

我不能肯定地说,因为AbstractFactory代码缺失,但它出现 CreateItemAbstractFactory中的模板方法,编译器无法确定调用哪个版本。

由于您没有显示所有代码,因此很难说清楚,但看起来您需要说CreateItem<T>()而不是CreateItem()。没有(常规)参数的函数模板不能推导出它的任何模板参数。