如何将结构体强制转换为char[]数组
How can i cast a struct to a char[] array?
我有一个类型为Blah
的变量。
我想将其强制转换为char[sizeof(blah)]
,而不复制。
我需要类型强制转换足够强,以实例化期望char[N]
的模板。
我已经尝试了很多方法,但是我都不太懂。
我想要这样的东西正常工作:
class Blah {
int a;
};
template <typename T>
void foo (T& a)
{
//Not an array
}
template <int N>
void foo (char(&a)[N])
{
//an array!
}
Blah b;
foo(b); //not an array
foo((char[sizeofBlah])b); //hopefully treated as an array
你不能执行这样的强制转换,这没有意义。可以做的是获取对象的地址,并将其重新解释为字节地址:
char* const buf = reinterpret_cast<char*>(&obj);
这应该满足您的要求,但是要注意使用术语"cast to char[]
",因为它混淆了正在发生的实际操作。
当然,你也可以把这个地址解释为固定大小缓冲区的起始地址:
using buffer_t = char[sizeof(Blah)];
buffer_t* pbuf = reinterpret_cast<buffer_t*>(&obj);
但是请注意,这里仍然使用指针指向缓冲区
您可以使用reinterpret_cast<char (&)[sizeof b]>(b)
执行此操作,但我不建议您这样做。
最干净的方法是将其作为操作添加到类中:
class Blah {
int a;
public:
void serialize(char *output) { output[0] = a; /* add others as needed */ }
};
Blah blah;
char buffer[sizeof(Blah)];
blah.serialize(buffer);
这将允许您明确地看到发生了什么,并集中代码,以防以后需要更改。
编辑:在我的示例中,序列化接口不是很优雅(或非常安全),但我的观点是,您应该将其作为方法添加。