c++模板包含使用相同类型T的对象
c++ template containing object using same type T
我有一个类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
代码缺失,但它出现 CreateItem
是AbstractFactory
中的模板方法,编译器无法确定调用哪个版本。
由于您没有显示所有代码,因此很难说清楚,但看起来您需要说CreateItem<T>()
而不是CreateItem()
。没有(常规)参数的函数模板不能推导出它的任何模板参数。
相关文章:
- std::unordered_map 类型对象声明期间出现"field has incomplete type"错误
- C++ 多态模板类,模板类型对象的实例化
- 如何分配适合容纳 T 类型对象的缓冲区(可能过度对齐、可能有运算符 new 等)
- 如何构造一个 std::variant 类型对象,其自身 Templated 和构造函数转发参数
- C++:初始化指向具有不同类型对象的指针数组
- 在类 C++ 中构造的模板类型对象
- 如何为同一类对象的成员函数保留单独的变量副本?
- 如何将颁发者名称设置为x509_req类型对象
- 将任何数据类型/对象作为参数传递以确定其大小
- 如何使用nullptr初始化同一类对象的静态指针数组?
- 将引用类型对象的数组从C#封送到C++
- <T> 从类型对象创建类型<T1>对象的构造函数
- RocksDB是存储同质对象的好选择吗
- C++是否有现有的方法来检查对象是否是派生类型对象
- C 模板:创建与现有对象相同的类型对象
- 链接列表中的虚函数 - 多种返回类型(对象)
- 没有适当操作员()的类型对象的呼叫
- 制作垫子类型对象的数组.输出窗口显示同一帧
- 抽象类型对象的分配
- 在std::list中就地创建自定义类型对象