C++ make a variable type depend on user input

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

    The simple answer is that you cannot, because data types need to be specifically declared at compile time.

    If you can use boost libraries,

    boost::variant vec;
    

    can suit your needs.

    You cannot use union because std::vector is not a POD (Plain Old Datatype).

    EDIT:

    As @Rob pointed out:

    Void pointers need to be converted into a pointer to something else - at compile time - before they can be used that way. So the answer is still "cannot" use void pointers to make a variable data type.

提交回复
热议问题