代码之家  ›  专栏  ›  技术社区  ›  prom85

通过另一个宏创建的函数创建所有列表的宏

  •  1
  • prom85  · 技术社区  · 8 年前

    我需要的是:

    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 )宏尚未解决此问题 init 函数不是由宏创建的),有什么想法可以创建init函数吗?定义静态列表并在宏本身中将项添加到此列表中不是解决方案(请查看背景信息以了解原因)。我需要一个宏,它创建一个列表,其中列出了使用 DEFINE_PARAM_CPP 宏。。。

    背景

    我的类正在实现一个接口,它将在另一个软件的插件api中注册。这意味着,我不能创建 IParam 在所有插件注册之前,api允许我创建 伊帕拉姆 对象(对象) 伊帕拉姆 对象通过另一个插件注册)。这意味着,我需要像现在这样懒洋洋地初始化我的列表。

    1 回复  |  直到 8 年前
        1
  •  2
  •   Andrew Kashpur    8 年前

    可以这样做:

    字段:h:

    current_macro(p1)
    current_macro(p2)
    current_macro(p3)
    

    经理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            
        }
    }