0
votes

I need to have a code which needs to use std::map and create a list of data types and its size. For example "BYTE" means 'unsigned char', "BOOL" means 'bool', "INT" means 'unsigned int', etc.

The input which I need to take from the user is string (datatype names) and from that I need to create the list. Once the user requests for a pointer for a specific datatype, I need to allocate memory and send the pointer back.

I found something on C++ std::map of template-class values. But I don't know how to initialize and use it. Is there an alternate way to do it. ( I am very new to template and std::map usage)

Thanks in advance.

1
I am not sure what you are asking but if you want to store any of those types in the same map you might want to look into boost::variant or boost::any. - NathanOliver
Why do you need to use std::map? I would try to solve the problem, and if map helps I would use it, but deciding to use map before you know how to solve the problem isn't a good idea. - Jonathan Wakely
C++ is a strictly typed language, so the "return" pointer should have a valid type, e.g. std::map<unsigned char> or std::map<unsigned int>. Each type is distinct and not part of any hierarchy. Can you post how you expect the user of your function to use the return value? - akhisp
You can store functions (e.g.: pointers) in your map which return a pointer to the allocated space. Would that solve your problem? Note: this smells like an xyproblem.info - Karoly Horvath
In general I need to have function which returns the allocated pointer for differenet datatypes and size. for example ALLOC(t, n) ((t *)malloc(sizeof(t) * n)). T * getpointer(std:string type, int size) { return(ALLOC(datatype[type],size));} assuming datatype is an std::map list - kar

1 Answers

1
votes

I think what you need is to provide a good buffer, and you what to wrap the buffer and provides a interfaces. I usually use std::vector as a big buffer(like a web page from the Internet), once contracted, use std::vector::data to access the pointer. Another way is to use "new" operator. It doesn't matter what data type you want to pass into. The size is automatically calculated once you provide the type. The old malloc() function will work too. One thing you have to remember is that after every "new", there should be a "delete". After every "malloc", there must be a "free". The interfaces could just be a void pointer, although it is not safe to do so.