我使用GCC 4.8.3和C++11。
我有一个
这是需求是不可更改的,因为它是一个更大的模板类的一部分,但是为了简化我的问题,它被分解了。
编辑:保证Endianess是正确的。谢谢。WhozCraig
我现在得到的是以下两个变体
template<typename T, int TupleIndex, unsigned int BufferPosition>
void extractBufferToTuple(T&& tuple, std::vector<uint8_t>&buffer) {
std::get<TupleIndex>(tuple) = *(typename std::tuple_element<TupleIndex,T>::type*)&buffer[BufferPosition];
}
和
template<typename T, int TupleIndex, unsigned int BufferPosition>
void extractBufferToTuple(T&& tuple, std::vector<uint8_t>&buffer) {
std::copy(&buffer[BufferPosition], &buffer[BufferPosition] + sizeof(typename std::tuple_element<TupleIndex,T>::type), (uint8_t*)&std::get<TupleIndex>(tuple));
}
调用它看起来像这样
std::tuple<uint32_t,uint32_t> myTuple;
std::vector<uint8_t> buffer;
buffer.resize(6);
uint32_t value0 = 123;
uint16_t value1 = 456;
std::copy((uint8_t*)&value0,(uint8_t*)&value0+sizeof(value0),&buffer[0]);
std::copy((uint8_t*)&value1,(uint8_t*)&value1+sizeof(value1),&buffer[sizeof(value0)]);
extractBufferToTuple<decltype(myTuple),0,0>(std::forward<decltype(testClass)::Tuple>(myTuple),buffer);
extractBufferToTuple<decltype(myTuple),1,sizeof(std::tuple_element<0,decltype(myTuple)>::type)>(std::forward<decltype(myTuple)>(myTuple),buffer);
是一个有效和安全的方法,还是有一些更好的实践,没有任何可能的陷阱?
也许是这样的:
template <typename T>
size_t extractBuffer(const std::vector<uint8_t>& buffer, size_t start_index, T* to) {
std::memcpy(to, &buffer[start_index], sizeof(*to));
return start_index + sizeof(*to);
}
template <typename ... Ts>
size_t extractBuffer(const std::vector<uint8_t>& buffer, size_t start_index,
std::tuple<Ts...>* to) {
auto extractHelper = [&](auto& ... elems) {
auto _ = {(start_index = extractBuffer(buffer, start_index, &elems)) ...};
return start_index;
};
return std::apply(extractHelper, *to);
}
演示