Need a data structure where I can map a string to a type

Hi,

Need a certain compile time map m like this:

 
using Type = typename m["Customer"]::type; // Type would be Customer 


How can i do this?

Regards,
Juan Dent
What forces you to have the type as a string?
Last edited on
I have the type as a string in the program- one for each table in the database
Last edited on
But if the string is fixed at compile time why can't you just use the type directly?

 
using Type = Customer;

Or pass it around using a template argument or whatever...


I don't understand why it needs to be a string unless the string can vary at runtime in which case you will need a different solution.
Last edited on
I don't know a way to do this directly. There are ways to do it indirectly (eg a union/variant or conditionally triggered) but if there is a slick way to do this without a middleman layer, I don't know the way.
the string is not known until runtime! I recall a structure in boost libraries that allowed this...
Last edited on
Well, in that case you would have to use some other technique to accomplish what you want. Consider using an enum instead of a string. You could use if/switch to select the correct behaviour. If different "types" use different "data" then you could use a union. Other alternatives are to use variants or inheritance.
Last edited on
one of the things I wish we had was a standard enum to string and string to enum construct. You can craft one easily enough, but the language seems bent on adding more stuff, this would be a candidate in my eyes. The stringify macro and using good enum names only gets you so far if you wanted a space character and lookup table of strings is awkward.

Boost has a lot that c++ does not... can you use it?
Last edited on
precisely I think boost must have the answer...
I remember doing something like this a couple of decades ago using a Factory pattern, but that was to actually create an object based on a key. And the classes of the objects being created all descended from a common base class.

However, I'm not sure if either of those conditions apply to the question at hand. Just something to consider.
It's not necessary to use an enum. It was just a suggestion.
Last edited on
Registered users can post here. Sign in or register to post.