I would like to define one or another static template-member function that would (explicitly) specialize in a data-pointer-element and could have a different return type for each specialization.
It should return some detailed information about each attribute, so I will call this trait
method. The return type of the object object is checked by other templates, so all equipment must be available at compile time.
So far, I have something like this (broken code, of course):
class Foo{ // some data members int a; std::string b; int c; // how to declare generic template here? // compile-time error should ensue if none of the specializations below is matched // specialization for a (aTraitExpr is expanded from macro, so it is OK to repeat it) template auto trait<&Foo::a>()->decltype(aTraitExpr){ return aTraitExpr; } // specialization for b; the return type will be different than for trait<&Foo::a> template auto trait<&Foo::b>()->decltype(bTraitExpr){ return bTraitExpr; } }; // some code which queries the trait at compile-time // eg supposing all possible trait types declare isSerializable // which happens to be True for a and False for b Foo* foo; template<bool isSerializable> void doSerialization(...); template void doSerialization<true>(...){ ... }; template void doSerialization<false>(...){ /* no-op */ }; doSerialization<Foo::trait<&Foo::a>()::isSerializable>(...); // -> doSerialization<true>(foo) doSerialization<Foo::trait<&Foo::b>()::isSerializable>(...); // -> doSerialization<False>(...) doSerialization<Foo::trait<&Foo::c>()::isSerializable>(...); // -> compile error, specialization Foo::trait<&Foo::c> not defined
Maybe a hint on how to achieve this? (I'm not trying to invent a new serialization system, I already use boost :: serialization, there will be more information in each characteristic, this is just an example of why this is necessary at compile time).
EDIT: I was able to get something closer to what I want shown on ideone.com . I declined to have trait<Foo::a>()
(for now), so there is a static function getTrait_a()
that returns a reference to modifiable types of types, which, however, are partially fixed at compile time (so Foo::TraitType_a::flags
works, for example). Thanks to everyone who answered, unfortunately, I can choose one of the answers as "answer".
source share