c++ - 创建给定模板的数组 (c++)

标签 c++ oop templates

最近在我的面向对象编程课上,我们正在处理模板。

在我们遇到的一个问题中,我们被要求创建一个可以存储任何类型的 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因为你不能将数组视为简单值。另外,使用newdelete对于这种任务来说,有一种代码味道。

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/

相关文章:

templates - Silverstripe - 是否可以在包含语句中使用变量?

Rcpp 中的 C++ 内置随机工件

c++ - 在编译时检测处理器是否有 RDTSCP

php - 将代码(方法)注入(inject)类?

python - 从列表中实例化一组类

c++ - 可变参数模板类型推导

c++ - decltype(function) 的类型是什么?为什么我不需要 "const"限定符?

c++ - 使用 std::shared_ptr 的 std::map 调用 const 重载函数

c++ - 检查字符串是否为数字,然后将该数字转换为 int?

通配符、基类和子类的 Java 泛型问题