C++ make a variable type depend on user input

前端 未结 4 1885
青春惊慌失措
青春惊慌失措 2021-01-18 02:41

I want a function that creates an array for testing purposes:

  • The idea es to make the user select the type of elements the array will contain (int, float, doub
4条回答
  •  青春惊慌失措
    2021-01-18 03:12

    it can be done using void* but in that case you need to do type casting yourself (as pointed out by @Rob) i.e. using reinterpret_cast operator or similar. Here is a simple example with void*

     void* vector(){
        int t;
        int op;
        cout << "Size: \n";
        cin >> t;
        cout << "Select type\n";
        cin >> op;
        switch(op) {
         case 0:
               // Create the array with the selected option...
                return  reinterpret_cast(new int[t]);
    
         case 1:
                // Create the array with the selected option...
                return  reinterpret_cast(new double[t]);
    
         default:
                // Other stuff;
                return  reinterpret_cast(new float[t]);
           }
        }
    

    Note: you can look at working of malloc() function, it always returns void* to allocated memory and you have to type cast it yourself e.g malloc(sizeof(int)*t)

提交回复
热议问题