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

前端 未结 1 1118
甜味超标
甜味超标 2021-01-12 23:39

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

template
CComPtr          


        
1条回答
  •  旧时难觅i
    2021-01-13 00:29

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

    template 
    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
    CComPtr CreateComObject()
    {
       CComPtr newObject( new CComObject );
       char(overflow)>());
       return newObject;
    }
    

    The value of sizeof(CComObject) 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++

    0 讨论(0)
提交回复
热议问题