2011-04-25 57 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