简体   繁体   中英

How can i cast a struct to a char[] array?

I have a variable of type Blah .

I want to cast it to char[sizeof(blah)] , without copying.
I need the type cast to be strong enough to instantiate a template that expects char[N] .

I've tried many things, but i can't quite get it.
I want something like this to work correctly:

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

You can't perform such a cast, that doesn't make sense. What you can do is get the address of the object and reinterpret the address as a byte address:

char* const buf = reinterpret_cast<char*>(&obj);

That should fulfil your requirements, but beware of using the terminology “cast to char[] ” because it obfuscates the actual operation that is taking place.

You can also interpret the address as the starting address of a fixed-sized buffer, of course:

using buffer_t = char[sizeof(Blah)];
buffer_t* pbuf = reinterpret_cast<buffer_t*>(&obj);

But notice that you are still using a pointer to the buffer here.

您可以使用reinterpret_cast<char (&)[sizeof b]>(b) ,但我不建议这样做。

The cleanest way would be to add it as an operation into the class:

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);

This will allow you to explicitly see what's going on and centralize the code in case you need to change it later.

Edit: The serialize interface is not very elegant (or very safe) in my example, but my point is that you should add it as a method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM