C++ make a variable type depend on user input

前端 未结 4 1843
青春惊慌失措
青春惊慌失措 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:19

    I think you should re-think your design.

    Rather than trying to write a function that returns an array of user-defined type to test. I would instead call a different test function depending on the user choice.

    The test function can be templated to avoid code duplication:

    #include 
    #include 
    
    template
    void doTest(unsigned size) {
    
        std::vector data(size);
    
        // Do the actual test on the data...
    }
    
    
    int main() {
        unsigned size;
        std::cout << "Size: \n";
        std::cin >> size;
    
        int op;
        std::cout << "Select type\n";
        std::cin >> op;
        switch(op) {
         case 0:
             doTest(size);
             break;
         case 1:
         default:
             doTest(size);
        }
    }
    

    If you really want to return your array from a function you could wrap it in a polymorphic type. But to actually do anything with the array you would need to call a virtual method on the polymorphic type so I don't see how it buys you anything over calling a test function directly.

提交回复
热议问题