2013-03-11 89 views
0

我試圖用宏來創建一些靜態變量。將模板宏定義爲變量

我的問題是,我該如何定義一個具有2個參數的宏,第一個是模板,第二個是靜態變量。模板應該有多於一種類型。

例如:

#define macro(x, y, z, v) x::y z = v; 

int main(int argc, char *argv[]) { 
    // this works 
    macro(std::queue<int>, value_type, test, 4) 
    // this also works 
    std::pair<int, int>::first_type x = 3; 

    // this is produsing some compiler errors 
    macro(std::pair<int, int>, first_type, test2, 4) 

    return 0; 
} 

,是它甚至有可能做到這一點?

這裏是錯誤:

main.cpp(47) : warning C4002: too many actual parameters for macro 'macro' 
main.cpp(47) : error C2589: 'int' : illegal token on right side of '::' 
main.cpp(47) : error C2589: 'int' : illegal token on right side of '::' 
main.cpp(47) : error C2143: syntax error : missing ',' before '::' 
main.cpp(50) : error C2143: syntax error : missing ';' before '}' 
main.cpp(51) : error C2143: syntax error : missing ';' before '}' 

由約阿希姆Pileborg

#define macro(x, y, z, v, ...) x<__VA_ARGS__>::y z = v; 
... 

// now it works 
macro(std::pair, first_type, test2, 4, int, int) 

THX約阿希姆

+0

你可以粘貼你得到的編譯器錯誤嗎? – 2013-03-11 15:06:20

回答

2

這是因爲,處理宏預處理程序是相當愚蠢的啓發。它在第二個宏「call」中看到五個參數,第一個是std::pair<int,第二個是int>。你不能有包含逗號的宏參數。

您可能想要查看variadic macros,並重新排列,以便該類在宏中最後一個。

2

這不是一個真正的解決方案,但只是一個變通:

#define COMMA , 

macro(std::pair<int COMMA int>, first_type, test2, 4) 

還是有點更具可讀性:

#define wrap(...) __VA_ARGS__ 

macro(wrap(std::pair<int, int>), first_type, test2, 4) 
2

有一對夫婦的方式來擺脫頂的級別逗號。

typedef std::pair<int, int> int_pair; 
macro(int_pair, first_type, test2, 4) 

macro((std::pair<int, int>), first_type, test2, 4); 

#define macro2(x1, x2, y, z, v) x1, x2::y z = v; 
macro2(std::pair<int, int> first_type, test2, 4) 

順便說一句,我會離開關從宏觀的;,並用它在任何地方使用的宏。這使得代碼看起來更自然。