1

我正在开发一个非常小的库,它将允许最终用户创建“命令”,可以通过在另一个函数中提供一个字符串来调用它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;
}
4

1 回答 1

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如果要执行多个操作,这会更自然地扩展。

于 2013-05-11T00:14:58.433 回答