sha*_*oth 6 c++ compile-time-constant compile-time visual-c++
视觉C++有#pragma message其输出一个字符串到编译器输出.现在我有一家工厂:
template<class Type>
CComPtr<Type> CreateComObject()
{
CComPtr<Type> newObject( new CComObject<Type> );
//do some tuning to the object
return newObject;
}
Run Code Online (Sandbox Code Playgroud)
我想输出传递给的类的大小new(即sizeof( CComObject<Type> )输入编译器输出.看起来#pragma message只接受字符串.
如何输出编译时数字常量?
如果我理解你的问题,那么我认为你可以这样做:
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;
}
Run Code Online (Sandbox Code Playgroud)
sizeof(CComObject<Type>)在编译期间,值将作为警告消息打印.
请参阅这个小型演示:http://www.ideone.com/Diiqy
查看这些消息(来自上面的链接):
prog.cpp:在成员函数'overflow :: operator char()[with unsigned int size = 4u ]':
prog.cpp:在成员函数'overflow :: operator char()[with unsigned int size = 12u ]':
prog.cpp:在成员函数'overflow :: operator char()[with unsigned int size = 400u ]'中:
在Visual Studio中,您可以在" 构建输出"选项卡中看到这些消息; 它可能不会出现在错误列表>警告选项卡中.
这个想法取自我的另一个解决方案: