3

I have the following template:

variable = config["variable"] ? config["variable"].as<type>() : default;

I want to create a macro to have this done for me faster, since writing this many times becomes boring. I would try something like:

#define CONFIG_PARAM(config, key, type, alt) config["key"] ? config["key"].as<type> : alt;

title = CONFIG_PARAM(root, "title", std::string, "")

It's obvious that that wouldn't work. How can I get this done?

Victor
  • 13,914
  • 19
  • 78
  • 147
  • #define AUX_VALUE(x) x █ #define QUOTATION_VALUE() " █ #define STRINGIFY(x) QUOTATION_VALUE()AUX_VALUE(x)QUOTATION_VALUE() █ #define CONFIG_PARAM(config, key, type, alt) config[STRINGIFY(key)] ? config[STRINGIFY(key)].as : alt; █ #define CONFIG_PARAM2(config, key, type, alt) config[key] ? config[key].as : alt; █ title = CONFIG_PARAM(root, title, std::string, "") █ title =CONFIG_PARAM2(root, "title", std::string, "") █ "█" is a line feed. – Joma May 14 '20 at 20:19

1 Answers1

9

To use strings inside a macro use this: #define str(s) #s This tells, that the argument has to use as a string

This is how to use ##

 #define COMMAND(NAME)  { #NAME, NAME ## _command }

 struct command
 {
   char *name;
   void (*function) (void);
 };

 // a call
 struct command commands[] =
 {
   COMMAND (quit),
   COMMAND (help),
   ...
 };

 // this expands to:
 struct command commands[] =
 {
   { "quit", quit_command },
   { "help", help_command },
   ...
 };
Alex44
  • 3,597
  • 7
  • 39
  • 56