sizeof如何工作?我如何写我自己? [英] How does sizeof work? How can I write my own?

查看:79
本文介绍了sizeof如何工作?我如何写我自己?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道C ++,知道函数 sizeof 本身,但我需要写我自己的sizeof函数,请解释它是如何工作的?

I know C++ and know the function sizeof itself but I need to write my own sizeof function so please explain how it works exactly? What does it do with the parameter?

推荐答案

你没有提供任何有意义的细节,你想做什么,因此很难弄清楚您需要什么。

You haven't provided any meaningful details about what it is you want to do, so it is hard to figure out what you need.

您可以通过自己的模板函数换行 sizeof like

You can "wrap" sizeof by you own template function like

template <typename T> size_t my_sizeof() {
  return sizeof(T);
}

,然后使用

size_t s = my_sizeof<int>();

有时可以遇到一个请求来实现类似sizeof的功能 / em>使用 sizeof 。这样的请求没有任何实际意义,但有时被用作家庭作业。可以这样做:

From time to time one can come across a request to implement sizeof-like functionality without using sizeof. Requests like that make no practical sense whatsoever, yet sometimes are used as homework assignments. One can probably do it as follows

template <typename T> size_t my_sizeof() {
  T t;
  return (char *) (&t + 1) - (char *) &t;
}

这将需要一个默认构造 code>。一个较少限制但正式非法的解决方案(一个黑客)将是像

which would require a default-constructible T. A less restricting but formally illegal solution (a hack) would be something like

template <typename T> size_t my_sizeof() {
  return (char *) ((T *) NULL + 1) - (char *) (T *) NULL;
}


$ b

The above implementations implement type-based sizeof.

尝试模拟基于价值的 sizeof 的功能可能如下所示

An attempt to emulate the functionality of value-based sizeof might look as follows

template <typename T> size_t my_sizeof(const T& obj) { 
  return my_sizeof<T>();
}

但这不会远远等于内置的 sizeof ,如果至少因为内置的 sizeof 不评估其参数。

but this will not be even remotely equivalent to the built-in sizeof, if at least because the built-in sizeof does not evaluate its argument.

最后,这些实现都不会产生积分常数表达式(ICE),因为内置的 sizeof 。在当前版本的语言中无法实现以这种方式生成ICE。

Finally, neither of these implementations will produce integral constant expressions (ICE), as the built-in sizeof does. Producing an ICE that way is impossible to achieve in the current version of the language.

在任何情况下,这一切,当然是完全没有任何实际价值。只要使用 sizeof 即可知道大小。

In any case this all, of course, is totally devoid of any practical value. Just use sizeof when you want to know the size.

这篇关于sizeof如何工作?我如何写我自己?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆