gpt4 book ai didi

c++ - 如何在 Visual C++ 编译期间输出编译时数字常量?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:32:39 30 4
gpt4 key购买 nike

Visual C++ 有 #pragma messageoutputs a string into compiler output .现在我有一个工厂:

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

我想输出传递给 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;
}

sizeof(CComObject<Type>) 的值将在编译期间打印为警告消息。


请看这个小演示:http://www.ideone.com/Diiqy

查看这些消息(来自上面的链接):

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]’:

在 Visual Studio 中,您可以在 Build Output 选项卡中看到这些消息;它可能不会出现在错误列表 > 警告 选项卡中。


这个想法来 self 的另一个解决方案:

Calculating and printing factorial at compile time in C++

关于c++ - 如何在 Visual C++ 编译期间输出编译时数字常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5775790/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com