2013-04-10 73 views
1

我有這個簡單的(無用)代碼來說明這個問題:C++宏和模板,多個參數錯誤

template<typename _Tx, typename _Ty> 
struct foo{}; 

#define TO_STRING(Type) #Type 

int main() 
{ 
    std::string sInt = TO_STRING(int); 
    std::string sfoo1 = TO_STRING(foo<int, float>); //warning and unexpected value - "foo<int" 
    std::string sfoo2 = TO_STRING((foo<int, float>)); //no warning, still unexpected value "(foo<int, float>)" 
} 

有沒有辦法通過使用多個參數的宏模板,而無需使用 ()

+0

不,沒有辦法。 – 2013-04-10 12:35:38

+0

你用什麼編譯它,所以當你將1或2個參數傳遞給宏時它會默默吞下? – 2013-04-10 12:37:51

+0

@RomanSaveljev Visual Studio 2010 – Felics 2013-04-10 12:39:21

回答

0

這可能不是很理想,但我認爲它完全可以在幾乎任何編譯器(如果你發現一個在它不,它很容易啞下來,沒有接口的改變):

#define TO_STRING1(_a_) #_a_ 
#define TO_STRING2(_a_, ...) #_a_ ", " TO_STRING1(__VA_ARGS__) 
#define TO_STRING3(_a_, ...) #_a_ ", " TO_STRING2(__VA_ARGS__) 
#define TO_STRING4(_a_, ...) #_a_ ", " TO_STRING3(__VA_ARGS__) 

唯一的缺點是你必須自己計算逗號,例如:

std::string sInt = TO_STRING1(int); 
std::string sfoo = TO_STRING2(foo<int, float>);