Click here to Skip to main content
15,887,875 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to define a map in c++ that have value as a class type?
Class type will be deifferent, i.e. generic.
Like below:

std::map<std::string, classtype=""> mapOfClass;

Here ClassType will be generic

What I have tried:

To define a map of class as a value
Posted
Updated 7-Feb-21 22:37pm

Documentation of std::map can be found at map - C++ Reference[^]

Generally, a map is made of a key and a value. It is a template class so the value is what ever you want to be. You must define a comparison function or lambda expression to compare objects of your class. That is central to the mapping process.

Here's an example of a type defining a class that maps an integer value using another integer as a key :
C++
using mintint = std::map< int, int >;
Here's another one that uses a character string as a key for integer values :
C++
using const char * = pcchar;
using mpccharint   = std::map< pcchar, int >;
 
Share this answer
 
The value in a std::map can be any object that is copyable so you can have a map where the key and value are both std::string. e.g.
C++
std::map<std::string, std::string>


but if you want to make the value generic, this is already handled as std::map is a template. But if you want an generic map where the key is always a string I think you have 2 options:

C++
template <class T>
class StringMap : public std::map<std::string, T>
{

}

With this solution you will need to define the constructors.

or you could try (requires C++17):
C++
using StringMap = std::map<std::string, std::any>;
 
Share this answer
 
The using keyword to accomplish this requires C++17.

C++
#include <iostream>
#include <map>
#include <string>

template<typename T>
using MyMap = std::map<int, T>;

int main()
{
    MyMap<int> myMap;
    myMap[3] = 4;

    std::cout << myMap[3] << "\n";

    MyMap<std::string> myTextMap;
    myTextMap[3] = "Hello";

    std::cout << myTextMap[3] << "\n";
}
 
Share this answer
 
Comments
Robin Imrie 8-Feb-21 7:09am    
I sure that would also work with C++11. But nice solution BTW.
Member 15025528 8-Feb-21 7:55am    
Thanks Robin
[no name] 8-Feb-21 10:33am    
-deleted-

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900