How do I output a compile-time numeric constant during compilation in Visual C++?

自古美人都是妖i 提交于 2019-12-19 07:07:10

问题


Visual C++ has #pragma message that outputs a string into compiler output. Now I have a factory:

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

and I want to output the size of class that is passed to new (namely sizeof( CComObject<Type> ) into the compiler output. Looks like #pragma message only accepts strings.

How can I output a compile-time numeric constant?


回答1:


If I understood your question correctly, then I think you can do this:

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;
}

The value of sizeof(CComObject<Type>) will be printed as warning messages during compilation.


See this small demo : http://www.ideone.com/Diiqy

Look at these messages (from the above link):

prog.cpp: In member function ‘overflow::operator char() [with unsigned int size = 4u]’:
prog.cpp: In member function ‘overflow::operator char() [with unsigned int size = 12u]’:
prog.cpp: In member function ‘overflow::operator char() [with unsigned int size = 400u]’:

In Visual Studio, you can see these messages in the Build Output tab; it may not appear in Error List > Warnings tab.


The idea is taken from my another solution:

Calculating and printing factorial at compile time in C++



来源:https://stackoverflow.com/questions/5775790/how-do-i-output-a-compile-time-numeric-constant-during-compilation-in-visual-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!