Search code examples
c++dictionarystlc++17stdany

using 'auto' in std::map


I'm parsing a JSON file, the values can consist of integer, string or float. Normally I have a map defined like this:

 std::map<std::string, std::string> myMap;

The problem is I'm not clear how to use map if there can be different data types, I tried:

 std::map<std::string, auto> myMap;

but I get an error:

'auto' is not allowed here

Is there I way I can use it with different data types or do I need to define an object, which can contain different data types, for example:

Class MyObject
{
  private:
    int integerValue;
    std::string stringValue;

  public:
    void setValue( std::string value, int type );
}

MyObject::setValue( std::string value, int type )
{
    if( type == 0 )
       stringValue = value;
    else if( type == 1 )
       integerValue = stoi( value );
}

Or is there a better way to do this? Thanks!


Solution

  • In order to achieve what you ask, use:

    std::map<std::string, std::any> myMap;
    

    For example:

    #include <map>
    #include <string>
    #include <any> // Since C++17
    
    main()
    {
        std::map<std::string, std::any> myMap;
    
        std::string strName{ "Darth Vader" };
        int nYear = 1977;
    
        myMap["Name"] = strName;
        myMap["Year"] = nYear;
    
        std::string strS = std::any_cast<std::string>(myMap["Name"]); // = "Darth Vader"
        int nI = std::any_cast<int>(myMap["Year"]); // = 1977
    }