【发布时间】:2020-05-01 23:20:09
【问题描述】:
在我的平台上,size_t 和 HDF5 的 hsize_t 都是无符号的 64 位整数,但它们是不同的 C++ 类型(一个是 unsigned long,另一个是 unsigned long long),不能互换使用。
using hsize_t = unsigned long long;
void library_function(const hsize_t*);
void client_code(std::vector<size_t> const&input)
{
library_function(input.data()); // error
}
所以我的问题是:在这种情况下是否需要转换
void client_code(std::vector<size_t> const&input)
{
std::vector<hsize_t> tmp(input.size());
std::transform(input.begin(), input.end(), tmp.begin(),
[](size_t x) { return hsize_t(x); });
library_function(tmp.data());
}
或者我可以简单地投射吗?
void client_code(std::vector<size_t> const&input)
{
static_assert(sizeof(size_t)==sizeof(hsize_t),"!!");
library_function(reinterpret_cast<const hsize_t*>(input.data())); // correct?
}
(这可以编译,但能保证正常工作吗?)
【问题讨论】:
-
即使在技术上是 UB,如果
library_function()在单独的翻译单元中实现,编译器也无法检测到严格的别名违规(除非您启用链接时优化),所以你可以使用reinterpret_cast。
标签: c++ casting type-conversion integer