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

Nov 9, 2024 at 8:28pm
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
Nov 10, 2024 at 8:17am
What forces you to have the type as a string?
Last edited on Nov 10, 2024 at 8:19am
Nov 10, 2024 at 12:18pm
I have the type as a string in the program- one for each table in the database
Last edited on Nov 10, 2024 at 4:48pm
Nov 10, 2024 at 8:36pm
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 Nov 10, 2024 at 8:42pm
Nov 10, 2024 at 8:39pm
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.
Nov 10, 2024 at 8:45pm
the string is not known until runtime! I recall a structure in boost libraries that allowed this...
Last edited on Nov 10, 2024 at 8:46pm
Nov 10, 2024 at 9:02pm
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 Nov 10, 2024 at 9:10pm
Nov 11, 2024 at 12:10am
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 Nov 11, 2024 at 12:11am
Nov 11, 2024 at 9:48am
precisely I think boost must have the answer...
Nov 11, 2024 at 1:33pm
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.
Nov 12, 2024 at 9:03am
It's not necessary to use an enum. It was just a suggestion.
Last edited on Nov 12, 2024 at 9:05am
Topic archived. No new replies allowed.