How to derive a numerical constant at compile time in Visual C ++?

Visual C ++ has a #pragma message that outputs a string to the compiler output file . 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 the class, which is passed in new (namely sizeof( CComObject<Type> ) to the compiler output. It seems that #pragma message only accepts strings.

How can I derive a numerical compile-time constant?

+6
source share
1 answer

If I understand your question correctly, I think you can do it:

 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 sizeof(CComObject<Type>) value sizeof(CComObject<Type>) will be printed as warning messages at compile time.


Check out this little demo: http://www.ideone.com/Diiqy

Check out these posts (from the link above):

prog.cpp: in the member function 'Overflow :: operator char () [with unsigned int size = 4u ]:
prog.cpp: In the member function 'Overflow :: operator char () [with unsigned int size = 12u ]:
prog.cpp: In the member function 'Overflow :: operator char () [with unsigned int size = 400u ]:

In Visual Studio, you can see these messages on the Assembly Output tab; it may not appear in the Error List> Alerts list.


The idea is taken from my other solution:

Calculating and printing factorial during compilation in C ++

+6
source

Source: https://habr.com/ru/post/886603/


All Articles