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

问题描述 投票:3回答:1

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

这里是我的队列

    #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);
c++ arrays templates queue
1个回答
0
投票

嗯,你快到了。您只需要不松开datanewQueue变量的范围。

template <typename T>
T input()
{
    T data;
    cout << "Enter an item to add" << endl;
    cin >> data;
    return data;
}
  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);
        newQueue->enqueue(input<int>());    
    }
    else if(choice == 2)
    {
        Queue<string> newQueue(MAXSIZE);
        newQueue->enqueue(input<string>());     
    }
    else if(choice == 3)
    {
        Queue<float> newQueue(MAXSIZE);

        newQueue->enqueue(input<float>());    
    }
    else
        cout << "Number needs to be 1-3." << endl;


}

0
投票

您需要运行时多态。解决这个问题。这可以通过基类或类似std::variant

的方法来实现。
class IQueue {
virtual ~IQueue() = default;
virtual void enqueue(istream&) = 0;
};

template<class itemType>
class Queue : public IQueue
{
private:
   unique_ptr<itemType []> queueArray;
    void enqueue(istream& is) override {
        itemType item;
        is >> item;
        enqueue(item);
    }
//...
};
© www.soinside.com 2019 - 2024. All rights reserved.