views:

146

answers:

3

hello

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.

+6  A: 

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++.

Potatoswatter
Also look at Boost.Fusion while you are at it. It's a good way to mix templates and runtime code. I have personally use `boost::fusion::map` as a skeleton for `struct` / `class` when I needed simili-reflection.
Matthieu M.
+1  A: 

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.

Michael Aaron Safyan
+1  A: 

You can't do that directly. The obvious question then, is what you're trying to accomplish -- chances are that you can do what you need to, but the way to do it may be rather different.

Jerry Coffin
actually, not really trying to do anything specific.Just thought how I could do it and realizing I do not know how, decided to ask a question. just trying to learn additional aspects.
aaa