将两个宏组合成一个/创建一个宏,在两个静态代码片段之间插入代码?

时间:2013-05-10 23:55:28

标签: c++ macros

我正在开发一个非常小的库,它允许最终用户创建“命令”,可以通过在另一个函数call("this_function",params);

中提供字符串来调用它。

我做得很好,但使用它的代码很难看:

#define begin(x) \
    class x\
    {\
        x(){/*some code*/}\
        void some_function_the_macro_has_to_make()

#define end() \
    }

begin(hello_world)
{
    /*do something*/
}
end();

我不知道如何在两个带宏的代码段之间插入代码,这是否可能?

(而且我对如何在没有宏的情况下实现这一目标知之甚少。)

所以我能做到:

#define begin(x){y} \
    class x\
    {\
        x(){/*some code*/}\
        void some_function_the_macro_has_to_make()\
        {\
            y\
        }\
    };

begin(hello_world)
{
    /*do something*/
}

如果没有,是否可能没有宏但有一些特殊的C ++东西?


编辑:
以下示例似乎有效,但在此问题的第二个代码示例中它没有实现我想要的内容:

#define begin(x,y) \
    class x\
    {\
        x(){/*some code*/}\
        void some_function_the_macro_has_to_make()\
        {\
            y\
        }\
    };

begin(hello_world,
        int x = 0;
        std::cout << "x:" << x;
);

    //it would be preffered to have:
begin(hello_world)
{
        int x = 0;
        std::cout << "x:" << x;
}

1 个答案:

答案 0 :(得分:1)

我不确定我是否完全理解您的目标,但我认为您希望避免使用end()宏。

如果是这种情况,您可以更改宏以定义class声明之外的方法。

#define begin(x) \
    class x\
    {\
        x(){/*some code*/}\
        void some_function_the_macro_has_to_make(); \
    }; \
    inline void x::some_function_the_macro_has_to_make ()

现在,您可以像这样使用它:

begin(hello_world) {
    int x = 0;
    std::cout << "x:" << x;
}

但我建议您考虑使用带有仿函数模板参数的模板。在进入下一个重要事项之后,代码可能对于必须维护代码的人更容易理解。有点像:

template <typename ACTION>
class ActionT
{
    ACTION action_;
public:
    ActionT() : action_() {/*some code*/}
    void some_function () { action_(); }
};

struct hello_world_action {
    void operator () () {
        int x = 0;
        std::cout << "x: " << x << std::endl;
    }
};

typedef ActionT<hello_world_action> hello_world;

如果class有多个要执行的操作,则会更自然地延伸。