Any good libraries or examples of doing exceptions good way?
I don't know, but it's pretty easy:
- create your own exception class(es)
- throw on exceptional case
- catch where it makes sense to handle the exceptional case
But in your example (function which returns a non-const reference to member), this is a programer error, not a runtime error, so I'd say you should treat this one with an assert -- maybe you could even static_assert with some tricks, as everything is known at compile time?
But this didn't work, because lambda which is passed to doForMember is instantiated for each MemberPtr and so line "age = memberPtr.get(person);" fails for all non-int types. Any tips about what I can do?
This is the kind of problems you'll run into with such a strongly-typed generic approach.
However I guess this one could easily be solved with a visitor:
class Visitor
{
template <typename T>
void visit(const Member<T>&)
{
}
void visit(const Member<int>& member)
{
do_something_with(member.get());
}
};
Visitor visitor;
visit(Meta<Person>::getMembers(), visitor); // for_each(member) visitor.visit(member)
This is the typical way to dispatch an heterogeneous container in a strongly-typed context.
This is just the idea, you'll now have to try to wrap this stuff so that it can carry all the needed context (age and person variables), and is more friendly on user-side (so you can use a simple lambda instead of writing a full visitor everytime).
The other typical approach is to introduce an intermediate weakly-typed layer (with a variant class for values, and abstract base classes on top of anything that depends on the underlying member type). But that's a different story.