c++ - 如何根据用户输入创建模板对象?

标签 c++ arrays templates queue

我使用模板制作了一个基于数组的队列,以便用户可以决定队列中保存什么类型的数据,但我无法弄清楚如何收集输入,然后从中创建该数据类型的队列。

这是我的队列

    #include <memory>
using namespace std;

template<class itemType>

class Queue
{
private:
   unique_ptr<itemType []> queueArray;
   int queueSize;
   int front;
   int rear;
   int numItems;
public:
   Queue(int);
   itemType peekFront();
   void enqueue(itemType item);
   void dequeue();
   bool isEmpty() const;
   bool isFull() const;
   void clear();
};

我已经尝试过这种方法和许多其他方法,但无法弄清楚如何判断用户输入的数据类型,然后使用该类型的数据创建一个队列。

    int main()
{
    const int MAXSIZE = 5;
    int choice;

    cout << "1. integer queue\n" << "2. string queue\n" << "3. float queue\n";
    choice = menu();

    if(choice == 1)
    {
        Queue<int> newQueue(MAXSIZE);
        int data;
    }
    else if(choice == 2)
    {
        Queue<string> newQueue(MAXSIZE);
        string data;    
    }
    else if(choice == 3)
    {
        Queue<float> newQueue(MAXSIZE);
        float data;     
    }
    else
        cout << "Number needs to be 1-3." << endl;

    cout << "Enter an item to add" << endl;
    cin >> data;

    newQueue->enqueue(data);

感谢大家的帮助!我几乎已经完成了,但是现在我已经拥有了所有虚拟函数,如何调用 peekFront() ?既然虚函数不能返回 itemType,对吗?

最佳答案

你需要运行时多态性来解决这个问题。这可以通过基类来实现:

class IQueue {
virtual ~IQueue() = default;
virtual void enqueue(istream&) = 0;
};

template<class itemType>
class Queue : public IQueue
{
//...
public:
    void enqueue(istream& is) override {
        itemType item;
        is >> item;
        enqueue(item);
    }
//...
};

并用作指针

int main() {
    //...
    unique_ptr<IQueue> newQueue;
    //...
    if(choice == 1)
    {
        newQueue.reset(new Queue<int>(MAXSIZE));
        int data;
    }
    //...
    newQueue->enqueue(cin);
    //...
}

或者像std::variant之类的东西。

关于c++ - 如何根据用户输入创建模板对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58928944/

相关文章:

c++ - 具有动态数组分配的 OpenMP 嵌套循环

arrays - Erlang 数组与列表

c++ - 无法在初始化时转换匿名枚举

c++ - std::array 编译时间扣除

c++ - std::unique_ptr 作为在 std::thread 中运行的参数

c++ - 如何用 Python 判断一个文件在 Windows 上是否可执行?

C++如何检查Shell输入的数量?

java - 我有一个 arrayList,其中每个元素都是 length 的整数数组。我如何在这里使用 .contains 方法?

c++ - 模板类继承

c++ - 非类型模板参数的链接器错误