C ++预处理程序宏,用于累积逗号分隔的字符串 [英] C++ preprocesor macro for accumulating comma-separated strings

查看:75
本文介绍了C ++预处理程序宏,用于累积逗号分隔的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要执行以下操作:

const char* my_var = "Something";
REGISTER(my_var);
const char* my_var2 = "Selse";
REGISTER(my_var2);
...
concst char* all[] = { OUTPUT_REGISTERED }; // inserts: "my_var1, my_var2, ..."

REGISTER和OUTPUT_located是preprocesor宏。这对于大量字符串(例如〜100)非常有用。

REGISTER and OUTPUT_REGISTERED are preprocesor macros. This would be great for large number of strings, like ~100. Is it possible to accomplish this?

PS。。该代码属于级别0块 –即,它不在任何函数内。 AFAIK,我无法在其中调用常规函数。

PS. The code belongs to level-0 "block" – i.e. it is not inside any function. AFAIK, I cannot call regular functions there.

推荐答案

#include <iostream>
#include <vector>
using namespace std;

vector<const char*>& all()
{
    static vector<const char*> v;
    return v;
}

struct string_register
{
    string_register(const char* s)
    {
        all().push_back(s);
    }
};

#define REGISTER3(x,y,sr) string_register sr ## y(x)
#define REGISTER2(x,y) REGISTER3(x,y,sr)
#define REGISTER(x) REGISTER2(x, __COUNTER__)

REGISTER("foo");
REGISTER("bar");

int main()
{
}

这篇关于C ++预处理程序宏,用于累积逗号分隔的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆