2011-04-25 59 views
6

Visual C++有#pragma messageoutputs a string into compiler output。現在我有一個工廠:。如何在編譯期間在Visual C++中輸出編譯時數字常量?

template<class Type> 
CComPtr<Type> CreateComObject() 
{ 
    CComPtr<Type> newObject(new CComObject<Type>); 
    //do some tuning to the object 
    return newObject; 
} 

,我想輸出傳遞到new(即sizeof(CComObject<Type>)到編譯器輸出類的大小看起來#pragma message只接受字符串

我怎麼能輸出?編譯時的數字常量

回答

6

如果我理解正確你的問題,那麼我認爲你可以這樣做:

template<size_t size> 
struct overflow{ operator char() { return size + 256; } }; //always overflow 
//if you doubt, you can use UCHAR_MAX +1 instead of 256, to ensure overflow. 

template<class Type> 
CComPtr<Type> CreateComObject() 
{ 
    CComPtr<Type> newObject(new CComObject<Type>); 
    char(overflow<sizeof(CComObject<Type>)>()); 
    return newObject; 
} 

在編譯期間,sizeof(CComObject<Type>)的值將被打印爲警告消息。


看這個小的演示:http://www.ideone.com/Diiqy

看看這些消息(從上面的鏈接):

prog.cpp:在成員函數 「溢出::運算炭() [with unsigned int size = 4u]':
prog.cpp:在 成員函數 'overflow :: operator cha R()[與 無符號整型大小= 12U]':
prog.cpp: 在成員函數 '溢出::運算炭()[與 無符號整型大小= 400U]':

在Visual Studio中,您可以在Build Output選項卡中看到這些消息;它可能不會出現在錯誤列表>警告選項卡中。


的想法是從我的另一種解決方案採取:

Calculating and printing factorial at compile time in C++

+1

@Nawaz,+1很好的答案,但它會給出編譯所有的編譯器警告一致? (不能是任何其他編譯器的錯誤或被忽略的消息?) – iammilind 2011-04-25 06:37:01

+0

@iammilind:由於溢出是有保證的,所以所有體面編譯都會生成這些警告消息(在我看來)。 – Nawaz 2011-04-25 06:38:01

+0

如果char超過八位,它不需要溢出。 gcc和Cormeau的在線編譯器都沒有提供這些警告。 – 2011-04-25 07:05:24