如何在Visual C ++中编译期间输出编译时数字常量? [英] How do I output a compile-time numeric constant during compilation in Visual C++?
问题描述
Visual C ++有 #pragma message
表示将字符串输出到编译器输出。现在我有一个工厂:
template< class Type>
CComPtr< Type> CreateComObject()
{
CComPtr< Type> newObject(new CComObject< Type>);
//做一些调整对象
return newObject;
}
,我想输出传递给 new
(即 sizeof(CComObject< Type>)
)看起来像 #pragma message
只接受字符串。
如何输出编译时数字常量?
如果我正确理解你的问题,我想你可以这样做:
模板< size_t size>
struct overflow {operator char(){return size + 256;}}; //总是溢出
//如果你怀疑,可以使用UCHAR_MAX +1而不是256,确保溢出
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:在成员函数
'overflow :: operator char()[with
unsigned int size = 4u ]':
prog.cpp:In
成员函数
'overflow :: operator char()[with
unsigned int size = 12u ]':
prog.cpp:
在成员函数
'overflow :: operator char()[with
unsigned int size = 400u ]':
在Visual Studio中,您可以在构建输出选项卡中看到这些消息;它可能不会出现在错误列表>警告标签中。
另一个解决方案:
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
(namelysizeof( CComObject<Type> )
into the compiler output. Looks like#pragma message
only accepts strings.How can I output a compile-time numeric constant?
解决方案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++
这篇关于如何在Visual C ++中编译期间输出编译时数字常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!