Reputation: 49231
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
Upvotes: 5
Views: 12460
Reputation: 545528
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.
Upvotes: 10
Reputation: 222362
You can do this with reinterpret_cast<char (&)[sizeof b]>(b)
, but I do not recommend it.
Upvotes: 6
Reputation: 27365
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.
Upvotes: 1