最近在我的面向对象编程课上,我们正在处理模板。
在我们遇到的一个问题中,我们被要求创建一个可以存储任何类型的 Queue 类
现在,当我想在此队列中存储某种数组时,我的问题就开始了,例如:
队列<字符*>
现在,当我想向队列中插入一个新的“节点”时,我不想创建一个指向内存块的双重指向。所以基本上我的问题是:“我如何创建一个与模板类指向的类型相同的数组?”
template<class T>
void Queue::enQueue(const T& value, int size = 1)
{
//exeptions handaling...
//handaling the case in wich the template is a pointer
if( _Is_pointer<T>() == true )
{
T temp = new T[size]; // i know its a mistake but thats what i basicly mean to do
for(int i = 0; i < size; i++)
temp[i] = value[i];
m_arr[++m_occupied] = temp; // m_arr is a data member of the T objects, m_occupied is as the name suggest
}
//...
}
感谢您的帮助:)
最佳答案
您可以使模板参数推导为您工作
// handling the case in wich the template is a pointer
template <class T> void Queue::enQueue(T const* value, int size = 1) {
这样,过载就推导出 T
作为 value
的对象类型指向。
现在,您可能想要 std::vector
因为你不能将数组视为简单值。另外,使用new
和delete
对于这种任务来说,有一种代码味道。
Guideline: In modern c++,
vector<>
is the default container for dynamically sized arrays,array<>
for fixed-size arrays.
// handling the case in wich the template is a pointer
template <class T> void Queue::enQueue(T const* value, int size = 1) {
m_arr[++m_occupied] = temp(value, value + size);
}
奖励如果您传递对数组的真实引用,您甚至可以推断出数组的大小:
// handling the case in wich the template is an array reference
template <class T, size_t Size> void Queue::enQueue(T const (&value)[Size]) {
m_arr[++m_occupied] = std::vector<T>(value, value + Size);
}
关于c++ - 创建给定模板的数组 (c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28004143/