2014-02-21 38 views
0

我有類似於下面的東西,這是我不太滿意:有沒有辦法編寫一個知道有多少次使用過另一個宏的宏?

#define BEGIN { 

#define END_1 }; 
#define END_2 END_1 }; 
#define END_3 END_2 }; 
// ... (possibly more of these) ... 

#define END(x) END_ ## x 

int main() 
{ 
    BEGIN 
    BEGIN 
    BEGIN 
    END(3) // <- I don't want to pass the 3 here 

    BEGIN 
    BEGIN 
    END(2) // <- I don't want to pass the 2 here 
} 

而且我想重寫的BEGIN和/或END這樣的定義,後者並不需要採取一種說法。

我相信這是做不到的,但我對預處理器不是很有經驗。至少有什麼辦法比我發佈的例子更接近我的目標?

+0

每次打電話給「BEGIN」時,都要打一個i ++,最後通過END(i)。只是一個建議。 – Abhineet

+1

@Abhineet:我真的不明白你的建議:(你可以用一些編譯代碼顯示你的意思嗎? –

+4

Wat,認真嗎?你正在使用宏...對於大括號...? – Puppy

回答

-4

不,沒有。

6

GCC和MSVC提供的非標準__COUNTER__宏隨着每次使用而增加。但是,無法重置它。

無論你試圖做什麼都應該做另一種方式。

3

以下可能會有所幫助: 它採用#include,而不是直接的宏...

begin.h:

#if !defined(BEGIN_COUNT) 
# define BEGIN_COUNT 1 
#elif BEGIN_COUNT == 1 
# undef BEGIN_COUNT 
# define BEGIN_COUNT 2 
#elif BEGIN_COUNT == 2 
# undef BEGIN_COUNT 
# define BEGIN_COUNT 3 
// And so on 
#else 
# error "Hard coded limit reached for BEGIN_COUNT" 
#endif 

// The token to add: 
{ 

end.h:

#if !defined(BEGIN_COUNT) 
# error "unbalanced #include begin.h/end.h" 
#elif BEGIN_COUNT == 1 
// The token to add: 
} 
#elif BEGIN_COUNT == 2 
// The tokens to add: 
} } 
#elif BEGIN_COUNT == 3 
// The tokens to add: 
} } } 
#else 
# error "Hard coded limit reached for BEGIN_COUNT" 
#endif 

// reset counter 
# undef BEGIN_COUNT 

,然後用它那方式:

int main() 
{ 
    #include "begin.h" 
    #include "begin.h" 

    #include "end.h" // close the 2 'begin' 

    #include "begin.h" 
    #include "end.h" // close the last 'begin' 
    return 0; 
} 
相關問題