C++ preprocesor macro for accumulating comma-separated strings

和自甴很熟 提交于 2020-01-13 22:35:53

问题


I need to do the following:

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 and OUTPUT_REGISTERED are preprocesor macros. This would be great for large number of strings, like ~100. Is it possible to accomplish this?

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


回答1:


#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()
{
}


来源:https://stackoverflow.com/questions/12095550/c-preprocesor-macro-for-accumulating-comma-separated-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!