C++确定变量的类型并在 sizeof() 中使用它
我想用 C++ 编写一个宏,它将值 0 赋予表的每个元素。例如,声明 i
如下:int i[10];
,宏 fill_with_zeros(i)
将产生以下效果:
i[0] = 0;
i[1] = 0;
等等。
这是它的代码:
#define fill_with_zeros(xyz) \
for(int l = 0 ; l < sizeof(xyz) / sizeof(int) ; l++) \
xyz[l] = 0;
问题是我希望它能够处理多种类型的表:char、int、double 等。为此,我需要一个函数来确定 xyz 的类型,这样我就可以使用类似 sizeof(typeof(xyz))
的东西来代替 sizeof(int)
。
存在类似的线程,但人们通常想要打印类型名称,而我需要在 sizeof() 中使用该名称。有什么办法可以做到吗?
提前致谢
I would like to write a macro in c++ which would give the value 0 to every element of a table. For instance, having declared i
thus: int i[10];
, the macro fill_with_zeros(i)
would produce this effect:
i[0] = 0;
i[1] = 0;
and so on.
This is its code:
#define fill_with_zeros(xyz) \
for(int l = 0 ; l < sizeof(xyz) / sizeof(int) ; l++) \
xyz[l] = 0;
The problem is that I want it to work with tables of multiple types: char, int, double etc. And for this, I need a function that would determine the type of xyz
, so that instead of sizeof(int)
I could use something like sizeof(typeof(xyz))
.
Similar threads exist but people usually want to print the type name whereas I need to use the name within sizeof(). Is there any way to do it?
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您应该按照其他人的建议使用 memset,但如果您确实想走宏路线:
You should use
memset
as others have suggested, but if you really want to go the macro route:或者,只需调用 memset(arr, 0, sizeof(arr));
我建议使用 memset 代替或 int i[10] = { 0 };
Alternatively just call
memset(arr, 0, sizeof(arr));
I would suggest using memset instead or int i[10] = { 0 };
为什么不直接使用
中的std::memset
呢?这就是它的设计目的,并且在大多数情况下工作得更快。Why not just use
std::memset
from<cstring>
? This is what it was designed for and will in most cases work a lot faster.为什么不直接使用
memset(xyz, 0, sizeof(xyz));
?对于所有内置类型(整数和浮点数),所有位 0 = 0。
Why not just use
memset(xyz, 0, sizeof(xyz));
?All-bits 0 = zero for all built-in types (integer and float).
数组的长度可以通过
sizeof(xyz) / sizeof(xyz[0])
确定。但是,已经有ZeroMemory
和memset
函数可以满足您的要求。The length of an array can be determined as
sizeof(xyz) / sizeof(xyz[0])
. However, there are alreadyZeroMemory
andmemset
functions that do what you want.你为什么认为你需要一个宏?这应该有效:
我希望我的 std lib 实现能够优化
std::fill()
以自行调用std::memset()
(或类似的东西)如果T
允许的话。请注意,这实际上并不将元素归零,而是使用默认构造的对象进行初始化。这对于所有可以归零的类型都实现了相同的效果,并且适用于许多不能归零的类型。
Why do you think you need a macro for that? This should work:
I'd expect my std lib implementation to optimize
std::fill()
to callstd::memset()
(or something similar) on its own ifT
allows it.Note that this does not actually zero the elements, but uses a default-constructed object for initialization. This achieves the same for all types that can be zeroed, plus works with many types that cannot.