Is it valid to cast integer to GLvoid* in C++20 using bit_cast?

别说谁变了你拦得住时间么 提交于 2019-12-10 16:56:02

问题


A previous question has asked for how to cast between integer types and GLvoid* in C++11 (based on the tags for that question) but here I'm interested in C++20.

Now that there is std::bit_cast as an option for doing type conversion, I'm wondering if it would be the "correct" way to use integers with OpenGL functions that for historical reasons take a GLvoid* to represent a byte offset (e.g. glDrawRangeElements), or whether the methods referenced at the previous question should be used instead.


回答1:


bit_cast is definitely the wrong thing here. void* is not required to be the same size as most integer types. bit_cast requires that the source and destination types have the exact same size. Therefore, on 32-bit systems, a std::bit_cast<void*>(24ull) is a compile error. While on 64-bit systems, a simple std::bit_cast<void*>(24) is a compile error.

And not even uintptr_t is required to have the same size as a pointer; only that it has at least as many bits as a pointer. If it has more, then bit_cast will choke on it.

Just do a reinterpret_cast<void*>, if you don't feel like using a C-style cast.




回答2:


No, although (with an appropriately-sized integer) it will often work in practice, and none of this is strictly-conforming anyway. This is a C API, so it means (void*)offset (in C). If your toolchain has the expected C compatibility), you can write that in C++, in which case it’s equivalent to reinterpret_cast<void*>(offset), but not necessarily to bit_cast<void*>(offset) (which preserves the bit pattern even if reinterpret_cast doesn’t and additionally requires that sizeof offset==sizeof(void*)).



来源:https://stackoverflow.com/questions/57579237/is-it-valid-to-cast-integer-to-glvoid-in-c20-using-bit-cast

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!