Boost logo

Boost Users :

From: remi.chateauneu_at_[hidden]
Date: 2005-03-17 15:23:07


Davi de Castro Reis wrote:

> So, here it goes. Is it possible to find the offset of a class member
> in compile time? In runtime, I can get the offset of member m1 in
> class A with the code
>
> offset = ((A *)0)->m1

You can use the macro :
offsetof(type, field)

... which returns qn int that you can use as an integer template
argument ...

> This would come very in hand for a metaprogramming based serialization
> library I am working on.

... but a much cleaner way is to use this C++ feature. This example
prints 1234.

#include <iostream>
template< class T, class S, S (T::*P) > struct printer {
        void operator()( const T & aT ) const { std::cout << aT.*P ; };
};
                                                                                          

struct X {
        int _i ;
        X() : _i(1234) {};
};
                                                                                          

int main(void) {
        X aX ;
        printer< X, int, &X::_i>()( aX );
        return 0 ;
}

This kind of library would be very useful for replacing some old and
dirty code generators. Some years ago, I started to work on this kind of
library, but missed some useful features like the ones Boost brought us.
Let me please describe quickly what it could do, if it can help :

* There was an object called a list of fields, defining, in a given
order, a list of some or all data members, getters, or base classes, of
a struct or class.
* It was possible to plug one or several different list of fields, to an
existing struct, without modification.
* On top of that, you had operator, which took as parameters a list of
fields, and an object of the struct associated to the list of fields. In
your example, there was a serializing operator.

To summarize, given a struct or class, you just needed one or several
list of fields, to be able to serialize these fields only, in a specific
order.

There were operators for serializing to a screen, creating 'CREATE
TABLE', 'INSERT' and 'SELECT' sql queries, writing to a network socket,
filling Windows dialogs, etc...

Feel free to take everything here (Sorry it is written in French) :
http://remi.chateauneu.free.fr/CPlusPlus/reflection/reflection.htm


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net