最近,我在一個項目中工作,該項目有很多使用宏生成的代碼。我遇到過這種情況,生成的代碼非常少。但是在這個當前的代碼中,有很多正在使用#define生成的代碼。 示例,類似於事件生成和處理以及爲類生成類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++來說,提供了這種提升。如果你真的對C感興趣,你可以看看我的包裝P99。 –
在這種特殊情況下,宏被用來污染代碼:-(。如果沒有它們,程序會更好。雖然在其他情況下使用宏也有很好的理由 – Serge