2

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!

Amit G.
  • 2,546
  • 2
  • 22
  • 30
0x29a
  • 733
  • 1
  • 7
  • 23

1 Answers1

3

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
}
Amit G.
  • 2,546
  • 2
  • 22
  • 30
  • Thanks! Looks like everything is working, except when casting the string, I get: "exception: std::bad_any_cast at memory location 0x0000001340EFA888", but all the other data types work properly, any suggestions please? Thanks! – 0x29a Apr 09 '19 at 15:10
  • @0x29a My example works for me, string & int. The exception occurred to you on the same example? – Amit G. Apr 09 '19 at 15:19
  • hmm strangely I had to wrap my variable inside std::string( myVar ); for it not to crash, that solved the problem, Thank you very much for your help!! – 0x29a Apr 10 '19 at 07:45