c++functionsyntax

How to convert a string or char* input to a data type in C++


In C++ I'm looking for a way to write a function that accepts two inputs:

char* typeName, int L

based on the typeName variable I will declare an array,

so if typeName is "int" I will declare and array of int in size L and if typeName is float I will declare an array of floats and so on...

And also I would like to be able to know when an invalid typeName was inputted and throw an exception.

Is there a more elegant way of doing so then if else statements ?


Solution

  • What you write sounds like this:

    void foo(std::string t, int L) {
         if (t == "int") {
               std::vector<int> vect(L);
         } else if (t == "float") {
               std::vector<float> vect(L);
         } else {
               // handle wrong type somehow
         }
    }
    

    However, this isn't very useful. Anything you want to do with one of the vectors has to happen within the respective branch. Note that I used std::string rather than char*, and std::vector instead of raw arrays, because that's the types you should use for strings and dynamically sized array. This wont change much about the question though.

    Let's say you can choose at compile time already what type of array to use, then you can do this:

     template <typename T,int L>
     auto foo() {
          return std::array<T,L>();
     }
    

    Now, because foo is a template, and choosing a different type to instantiate it will result in a separate function, there are no arrays of different types in one function. foo<int>() can return an array of integers and foo<float> can return an array of floats. Because, array sizes must be compile time constants, I made L a template argument too.

     std::array<int,42> arrayi = foo<int,42>();
     std::array<float,42> arrayf = foo<float,42>();
    

    On the other hand, there is no out-of-the box mapping between a runtime value and a type. The return type of a function is part of the function declaration. If you declare a variable you must choose what type it should be. That doesn't mean that C++ cannot do this at all. A pointer to a base class can point to instances of any type that derives from the base for example. Arrays of elements of different type have no common base though. Another way of type erasure is std::variant or std::any. It's too broad a topic to go into details. The solution to choose depends on the concrete problem at hand.