amir hajizadeh
amir hajizadeh

Reputation: 125

size of fields of a c++ struct

I have various c++ struct in my program, I want a function to accept one of this struct's in input and get me in a int array contain size of each fields of input struct in byte. ca any one help me?

Upvotes: 1

Views: 513

Answers (2)

Nim
Nim

Reputation: 33655

Here is an approach:

Use an overloaded function, and in each overload (for each struct), explicitly insert the size of each field from that struct into the passed in array (vector<size_t> is better alternative).

This means effectively you have to hard-code the fields in each structure in each overload.

Alternatively, if you are happy to use boost::fusion, with a few macros, you should be able to promote the structure - which you can then iterate over. I've posted an answer with an example somewhere on SO, will dig it up...

Here it is: Boost MPL to generate code for object serialization?, shows how to "promote" the structure and then iterate over the members. In that case, it's for serialization, but it's trivial to adapt it to return the size of each field. You could do this with MPL at compile time and generate an MPL sequence with the size of each field - but that's a little more tricky - it all depends on what you want to achieve really...

Upvotes: 1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272477

That's not possible.1 C++ does not have reflection.


1. To be precise, it's not possible to have this done automatically by the language. You could, of course, keep track of this stuff manually (as in @Nim's suggestion).

Upvotes: 3

Related Questions