Search code examples
c++type-conversionabstract-data-typecustom-data-type

How to detect data types from string?


There is a pseudocode:

s = input()

if s == 'int':
    func<int>(...)
if s == 'char':
    func<char>(...)
and there're more if blocks

How can I write code that can do this without any if. Like code below:

s = input()
func<s>(...) #auto detect type in s

I need a solution in C++.


Solution

  • Although this is not directly possible with templated functions, I recommend a table lookup of std::string vs. function pointer.

    For example:

    typedef void (*Function_Pointer_Type)(void);  
    struct Table_Entry
    {
      char const * data_type_name;
      Function_Pointer_Type data_type_function;
    };
    
    void Process_Int(void);
    void Process_Double(void);
    
    static const Table_Entry data_type_function_table[] =
    {
      {"int", Process_Int},
      {"double", Process_Double},
    };
    static const unsigned int number_of_data_types =
      sizeof(data_type_function_table) / sizeof(data_type_function_table[0]);
    
    // ...
    for (unsigned int i = 0; i < number_of_data_types; ++i)
    {
      if (s == data_type_function_table[i].data_type_name)
      {
        data_type_function_table.data_type_function();
        break;
      }
    }
    

    Another method is to use std::map<std::string, Function_Pointer_Type>. The map must be initialized before it is used. The static, constant table doesn't need to be initialized at runtime.