2

I've go the following code:

#include <string>
#include <map>
#include <vector>

typedef std::map<std::string, std::map<std::string, std::map<std::string, std::string> > > SCHEMA;

int main() {
    SCHEMA tables;

    // Schema table
    tables["table_name"]["row_id"]["field_name"] = "value";
}

I want to modify the typedef to have a "row_id" as a numeric index and value of any type (kind of auto detecting). What should I do to achieve something like this?

tables["table1"][0]["field1"] = "value of any type";
user3050705
  • 457
  • 1
  • 5
  • 13

1 Answers1

1

Numeric index is easy, just replace std::string with int. "Value of any type" can be tricky to get right C++, and can lead to problem if not done carefully. You could use void * (bad) or a union (ok), but a better option would probably be some variant implementation, e.g. boost::variant, so the typedef would read, for example:

typedef std::map<std::string, std::map<int, std::map<std::string, boost::variant<int, std::string> > > > SCHEMA;
aquavitae
  • 17,414
  • 11
  • 63
  • 106
  • Boost is not available on school machine. Could you give an example of union based on my code? – user3050705 Dec 04 '13 at 17:06
  • There are plenty of resources on the Internet explaining how to use a union, but really I would either use boost::variant or create my own. Union might do the job, but it's not really the right tool. – aquavitae Dec 05 '13 at 04:48