【发布时间】:2018-01-03 06:41:59
【问题描述】:
最近,我在一个项目中工作,其中有很多使用宏生成的代码。我遇到过这样的情况,生成的代码非常少。但是在当前这个版本中,有很多代码是使用 #defines 等生成的。 示例,例如用于事件生成和处理的类以及为类生成类 Id。
#define INIT_EVENT_INFO(eventType) \
template <> const GenericClassID eventType::tClassID(#eventType) ;
#define DECLARE_EVENT(dType, evtType, destnType) \
typedef DUMMY_EVT_GEN<dType, std_event, custom_destn, destnType>::EventClass evtType;
template <typename ctData,
EventTypes evType,
DestnTypes evtDestType = standard_destn,
class DestnInterface = EmptyClass>
class DUMMY_EVT_GEN
{
private:
// alias for our current generator
typedef DUMMY_EVT_GEN<ctData,
evType,
evtDestType,
DestnInterface> Generator;
// Construct the first layer by adding the data part to our
// framework event base class.
//
typedef BaseEvent::DerivedEvent<Generator> CompleteEvent_;
/*
* Assemble an event destn type
*/
// Determine base class for event Destn: RTTIEventDestn for
// rtiDestns
typedef typename IF<isRtiDestn, BRTTIEventDestn, EventDestn>::type DestnBase_;
// create event Destn type
typedef typename IF<isCustomDestn, DestnInterface, BaseEvent::THBDestn<Generator> >::type DestnType_;
public:
/**
* A struct that contains all configuration options
*/
struct Config
{
/// base class for the Destn (rti or not)
typedef DestnBase_ DestnBaseClass;
/// class serving as data container for the event type
typedef ctData EventDataClass;
/// the resulting event type
typedef CompleteEvent_ EventClass;
/// the resulting Destn interface type
typedef DestnType_ DestnInterface;
};
// our final return values
typedef typename Config::EventClass EVT;
typedef typename Config::DestnInterface DestnInterface;
typedef typename Config::EventClass EventClass;
};
现在,我的问题是,有没有一种特定的方式已经定义了这些东西。
哈希定义可以随意使用。 但是,是否有任何定义的模式或方法来编写这样的代码,这有助于我们生成这样的代码。不仅是这种情况。还有许多其他场景,可以编写此类代码并将其用于自动生成类、事件、结构等。
作为一名程序员,如何考虑编写这样的宏来减轻我们的工作量。它确实来自实践,但是否有任何特定的方式或模式 或任何帮助我们以这种方式编程的文档,我的意思是考虑使用此类宏进行编程。
任何指示或建议都会有很大帮助。
【问题讨论】:
-
对于 C++,有提供此功能的 boost。如果你真的对 C 的那个感兴趣,你可以看看我的包 P99。
-
在这种特殊情况下,宏用于污染代码:-(。没有它们,程序会更好。尽管在其他情况下使用宏有充分的理由。
标签: c++ class macros code-generation