C++ 连续内存中的模板化可变大小结构

Templated varying size structures in contiguous memory in C++

我面临以下问题。我想制作一个可以处理尽可能多的结构的模板函数,但它有一个限制,即它需要能够将所有数据连续复制到缓冲区中。

例如:

struct A{
    int foo;
    int bar;
}

应该变成一个8字节的缓冲区。

struct B{
   int foo;
   vector<int> bar;
}

B.bar = vector<int>(2);

应该成为一个 12 字节的缓冲区。

对于B的情况,如果我已经知道B的样子,我可以调用malloc()分配12个字节,然后手动将数据复制到这个缓冲区。

有没有一种方法可以通过模板来实现这一点,或者我是否需要添加一个限制,即为我的模板化函数提供的任何结构都必须已经连续存储?

编辑:

这就是我所说的将B的数据复制到一个缓冲区中。

int *buffer = (int*) malloc(sizeof(int)+sizeof(int)*bar.size());

buffer[0] = foo;

for(int i=0; i<B.bar.size(), i++)
    buffer[i+1]=B.bar[i];

在post,你说,

I want to make a templated function that can handle as many structures as possible

在你说的评论中,

I am writing a wrapper for OpenGL SSBOs, and thus I require to pass the data to the GPU as a contiguous packet. The use case for this function is to be able to generally compact the data and pass it to the GPU

objective 是有道理的。使用函数模板到达那里的策略可能不正确。

使用重载函数可能是您的最佳选择。

using BufferData = std::vector<char>;

BufferData toBufferData(A const& a);
BufferData toBufferData(B const& b);