Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is it possible in C++ to determine number of variables/fields in the generic class? for example

// suppose I need metaclass number_members determines number of members

struct example { int i, j; };
assert(number_members<example>::value==2);

I looked through mpl but could not find implementation.

thanks.

like image 456
Anycorn Avatar asked Apr 07 '10 03:04

Anycorn


2 Answers

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

You can try a C++0x std::tuple, which has some of the features of a general POD struct. Or, try to roll your own from the Boost MPL library. That would be a bit advanced if you're just getting started with C++.

like image 162
Potatoswatter Avatar answered Sep 29 '22 20:09

Potatoswatter


No. Unfortunately, C++ does not have that kind of introspection builtin. However, with some additional preprocessing such as Qt's Meta Object Compiler (moc), you can achieve something similar... the QMetaObject class provides a propertyCount(); however, your class would need to inherit from QObject, use the Q_OBJECT macro, and register the properties for all that to work... so, in short, it's not automatic.

like image 28
Michael Aaron Safyan Avatar answered Sep 29 '22 20:09

Michael Aaron Safyan