【发布时间】:2014-03-17 14:04:06
【问题描述】:
我想编写一个函数来从二进制缓冲区中提取一些数据(假设数据是按顺序存储的)。该函数返回数据和提取数据后的指针,如下所示
std::tuple<const unsigned char *, int, double, float> data = Extract<int, double, float>(p_buffer);
它从p_buffer 中提取int、double 和float 数字,data 的第一个值指示下一次提取工作的开始位置。
我试着写这样的东西。
#include <tuple>
typedef unsigned char byte;
template<class TFirst, class... TRest>
struct Extractor
{
static std::tuple<const byte *, TFirst, TRest...> Extract(const byte *p_current)
{
TFirst first_value;
TRest... rest_values; // Not working.
std::tie(p_current, first_value) = Extractor<TFirst>::Extract(p_current);
std::tie(p_current, rest_values...) = Extractor<TRest...>::Extract(p_current);
return std::make_tuple(p_current, first_value, rest_values...);
}
};
template<class T>
struct Extractor<T>
{
static std::tuple<const byte *, T> Extract(const byte *p_current)
{
return std::make_tuple(p_current + sizeof(T), *reinterpret_cast<const T *>(p_current));
}
};
它无法编译,因为“参数包无法在此上下文中展开”。我听说函数模板不能部分特化,所以我使用结构。如何让它发挥作用?
【问题讨论】:
-
请不要说“不行”。
-
使返回值成为
char*的命名类型,后跟一个元组,而不是一个大元组。或两层元组。在其他地方进行类似的更改以将类型保留在元组 esp 包中。而且应该很容易。
标签: c++ templates c++11 tuples variadic-templates