Gio*_*ani 2 c++ pointers c++14
我有这个模板功能
template <typename T, typename It, std::enable_if_t<std::is_integral<T>::value, int> = 0>
inline T decode(It &it) {
static_assert(std::is_same<typename std::iterator_traits<It>::value_type, std::uint8_t>::value, "invalid");
T* v_p = reinterpret_cast<T*>(&*it);
it += sizeof(T);
return *v_p;
}
Run Code Online (Sandbox Code Playgroud)
用于从原始指针解码整数。该函数可以与任何具有迭代器特征的类型一起使用,即指向具有满足LegacyContiguousIterator要求的迭代std::uint8_t器的std::uint8_tSTL 容器的指针或迭代器。
该函数有效,但我不确定调用&*itwhenit是指针的性能。需要运算符来从迭代器获取指针,如本答案中所述,但对于 POD 指针来说似乎有点过分。是否允许编译器只删除操作,或者最好为指针编写专门化