2017-07-27 83 views
0

最近,我在一個項目中工作,該項目有很多使用宏生成的代碼。我遇到過這種情況,生成的代碼非常少。但是在這個當前的代碼中,有很多正在使用#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; 
}; 

現在,我的問題是,是否有一個具體的方式,已經定義了這樣的事情。

哈希定義可以用於自己的自由。 但是,是否有任何定義的模式或方式來編寫這樣的代碼,這有助於我們生成這樣的代碼。不僅這種情況。還有很多其他場景,可以編寫這樣的代碼並用於自動生成類,事件,結構等。

作爲一名程序員,如何考慮編寫這樣的宏,這將減輕我們的工作量。它確實來自實踐,但有沒有任何特定的方式或模式或任何可幫助我們編程的文檔,我的意思是使用這些宏編程。

任何指針或建議將會很有幫助。

+0

對於C++來說,提供了這種提升。如果你真的對C感興趣,你可以看看我的包裝P99。 –

+0

在這種特殊情況下,宏被用來污染代碼:-(。如果沒有它們,程序會更好。雖然在其他情況下使用宏也有很好的理由 – Serge

回答

0

這只是我的想法,它不適合簡單的回覆:-)。 C++,尤其是c11及以上版本增加了很多功能,用一個可控制的基於編譯器的生成器代替宏,以模板開始,以constexpr結尾。這是一個比宏更強大的機制,儘管它通常需要更多文本來表達意圖。無論如何,由於這個原因需要在馬可,大大減少了c。我發現實際上有3個與C++一起使用的理由。

  1. 隱藏語言中實現特定的細節。即gcc中的函數或結構屬性,這可能不會在其他編譯器中實現或實現不同。使用#define PACKED __attribute((packed))__
  2. 條件編譯出於不同的原因,比如在頭文件中後衛宏:​​
  3. 很方便的宏,免去重複的代碼比較大塊不以功能吻合,尤其是當你需要的東西轉換一個字符串。即#define tostr(A) case A: return #A;
+0

感謝您的回答。使用這些宏,但有沒有任何特定的模式或宏的任何明確的編碼或使用指南,有助於學習這種編碼風格,並將其應用於其他地方我也在Windows事件生成機制中看到過這樣的代碼,但在這裏大部分代碼是使用這些宏生成的,我只是想知道在什麼情況下應該使用這些宏,並且是否存在任何可以遵循的特定模式 – TechTotie

+0

建議是:不要使用宏,除非你絕對**需要他們不知道是否有更好的指導方針:-)。您可能會找到一些特定於組織的指導原則,但不包括整個行業。我想大家都同意的唯一的事情是(或多或少)是宏的首字母NAMES。其餘的是個人的。 – Serge

+0

謝謝你的意見。 – TechTotie