C ++ template meta-programming, the number of member variables?

Is it possible in C ++ to determine the number of variables / fields in a common class? eg

// suppose I need metaclass number_members determines number of members struct example { int i, j; }; assert(number_members<example>::value==2); 

I looked at mpl but could not find an implementation.

thanks.

+6
c ++ templates metaprogramming
source share
3 answers

Not. C ++ does not provide general introspection into structures.

You can try C ++ 0x std::tuple , which has some features of the general POD struct . Or try flipping your version from the Boost MPL library. This will be a bit advanced if you are just starting out with C ++.

+7
source share

Not. Unfortunately, C ++ does not have such an introspection. However, with some additional preprocessing, such as the Qt Meta Object Compiler (moc) , you can achieve something similar ... The QMetaObject class provides propertyCount () ; however, your class must inherit from QObject , use the Q_OBJECT macro and register properties for everything that works ... therefore, in short, it is not automatic.

+1
source share

You cannot do this directly. Then the obvious question is what you are trying to accomplish - most likely, you can do what you need, but the way to do this can be completely different.

+1
source share

All Articles