这就是我需要的:
class Manager
{
private:
IParam *p1;
IParam *p2;
IParam *p3;
std::vector<IParam*> allParams;
public:
void init()
{
// init allParams list, simply calling all getter is enough here
getP1();
getP2();
getP3();
}
IParam *getP1()
{
if (p1 == NULL)
{
p1 = new IParam("p1");
allParams.push_back(p1);
}
return p1;
}
IParam *getP2()
{
if (p2 == NULL)
{
p2 = new IParam("p2");
allParams.push_back(p2);
}
return p2;
}
IParam *getP3()
{
if (p3 == NULL)
{
p3 = new IParam("p3");
allParams.push_back(p3);
}
return p3;
}
}
我的宏看起来如下:
#define DEFINE_PARAM_CPP(NAME) \
private: \
IParam * NAME; \
public: \
IParam * get##NAME() \
{ \
if (NAME == NULL) \
{ \
NAME = new IParam("NAME"); \
allParams.push_back(NAME); \
} \
return NAME; \
}
问题
如您所见,我需要初始化一个向量(allParams
)。宏还没有解决这个问题(宏不创建{{1}}函数),任何想法如何创建init函数?定义静态列表并在宏本身中将项添加到此列表是没有解决方案(检查背景信息以找出原因)。我需要一个宏来创建一个用init
宏创建的所有函数的列表......
背景
我的类正在实现一个接口,它将在另一个软件的插件API中注册。这意味着,在注册所有插件之前,我无法创建DEFINE_PARAM_CPP
的实例,并且API允许我创建IParam
个对象(IParam
个对象通过另一个插件注册)。这意味着,我需要像我目前那样以懒惰的方式初始化我的列表。
答案 0 :(得分:2)
可以这样做:
fields.h:
current_macro(p1)
current_macro(p2)
current_macro(p3)
manager.h
class Manager{
private:
#define current_macro //how you want define elements
#include fields.h
#undef current_macro
std::vector<IParam*> allParams;
public:
#define current_macro //how you want your getter to look like
#include fields.h
#undef current_macro
void init()
{
#define current_macro //how you want your part of init look like
#include fields.h
#undef current_macro
}
}