我有以下模板:
variable = config["variable"] ? config["variable"].as<type>() : default;
Run Code Online (Sandbox Code Playgroud)
我想创建一个宏来更快地完成这项工作,因为写这么多次变得很无聊.我会尝试类似的东西:
#define CONFIG_PARAM(config, key, type, alt) config["key"] ? config["key"].as<type> : alt;
title = CONFIG_PARAM(root, "title", std::string, "")
Run Code Online (Sandbox Code Playgroud)
很明显,那是行不通的.我怎么能这样做?
要在宏中使用字符串,请使用:#define str(s) #s这告诉参数必须用作字符串
这是怎么用的 ##
#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 },
...
};
Run Code Online (Sandbox Code Playgroud)