0

Hey I'm new with c++ and I'm trying to create a map wich can store multiples types :

map<sting, `auto`> test_map;
test_map["first elem"] = 1;
test_map["second elem"] = 'c';

Wich obviously gets me some errors.

I've been looking a bit online and I have found interesting things but not an answer. Maybe I miss a bit of c++ vocabulary.

I would also try with some kind of class wich stores about any types and I don't know if it can works.

map<string, `my_class`> test_map;
map["first_elem"] = my_class("string");
map["first_elem"] = my_class(12); 

Thank you for helping !

wartonbega
  • 129
  • 6
  • 6
    Maybe [std::any](https://en.cppreference.com/w/cpp/utility/any) would help you here? – Galik Aug 21 '21 at 11:34
  • 3
    *"some kind of class wich stores about any types"* Those classes already exist: `std::variant`, `std::any`. The first one has much more reasonable interface, but requires all possible types to be known in advance. – HolyBlackCat Aug 21 '21 at 11:35
  • Perhaps `std::map` isn't the correct container for your problem, whatever it might be? – Some programmer dude Aug 21 '21 at 11:36
  • or `std::variant` if you limit yourself number of supported types (as in json libraries). – Jarod42 Aug 21 '21 at 11:36
  • std::map> https://stackoverflow.com/questions/50210104/iterate-through-a-map-of-stdvariant – Pepijn Kramer Aug 21 '21 at 11:36
  • @Someprogrammerdude std::map is the right container, I can access some values with just a string. – wartonbega Aug 21 '21 at 13:10
  • Using a string to access some data doesn't automatically mean `std::map` is the correct container-type. If that's the only requirement you have then perhaps you should consider writing your own container-type that can handle all your requirements? – Some programmer dude Aug 21 '21 at 14:52

1 Answers1

4

The auto keyword doesn't mean you can assign multiple value types to the same storage, it's merely an automatic type deduction tool in c++ useful when you deal with complex type names or purely unwritable types (such as capturing lamdas) eg.:

void foo()
{
    bool b = true;
    auto l = [&]() -> bool { return !b; };
}

If you want to store values of different (or any) types in the same storage space try using either std::varian or std::any (both require c++17 or higher).

std::variant allows you to store one of the earlier specified types and doesn't do additional allocations (it's size is enough to hold any object of specified type). It's a type safe alternative to unions.

void foo()
{
    std::map<std::string, std::variant<int, float, char>> c; // this can only map int, float and char to std::string
}

std::any can store any type you want but will allocate when necessary.

void foo()
{
    std::map<std::string, std::any> c; // this can map any type of value to std::string
}
Marcin Poloczek
  • 923
  • 6
  • 21