[英]Code generation using preprocessor macros
最近,我在一個項目中工作,該項目具有許多使用宏生成的代碼。 我遇到過這樣的情況,其中生成的代碼非常少。 但是在當前版本中,有很多代碼是使用#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 ++,特別是c11及更高版本,添加了許多功能,以可控的基於編譯器的生成器替換宏,從模板開始,以constexpr結尾。 盡管通常需要更多文本來表達意圖,但它是一種比宏強大得多的機制。 無論如何,由於這個原因,與c
相比,對marcro的需求大大減少了。 我看到將它們與c ++一起使用的3個很好的理由
#define PACKED __attribute((packed))__
#ifndef MY_HDR .. #define MY_HDR ... #endif
#define tostr(A) case A: return #A;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.