How can I infer the external type of the internal type in C ++?

I have many classes displaying an internal type called Binding . For example, one of them may be:

 struct Message { struct Binding { }; }; 

I call the apply function as follows:

 apply< Message >([](Message::Binding& x) { // setup binding fields }); 

I wrote

 template <class TMessage, class TBindingExpression> void apply(const TBindingExpression& expr) { typedef typename TMessage::Binding BindingType; BindingType binding; expr(binding); apply(MessageUtil::typeId< TMessage >(), binding); } 

Since Message bit redundant in the way I invoke apply , I would like to draw the output of the Message compiler so that I can write

 apply([](Message::Binding x) { //... }); 

So far, I'm stuck here:

 template <class TBindingExpression> void apply(const TBindingExpression& expr) { // I get the type of the argument which is Message::Binding in this example typedef typename std::tuple_element < 0, FunctionTraits< TBindingExpression >::ArgumentTypes > ::type BindingType; // so I can invoke my expression BindingType binding; expr(binding); // But now I need the type of the outer class, ie Message typedef typename MessageTypeFromBinding< BindingType >::Type MessageType; apply(MessageUtil::typeId< MessageType >(), binding); } 

Is there any way to write / achieve a MessageTypeFromBinding ?

Obviously, this is purely curiosity and cosmetic problems.

+4
c ++ templates metaprogramming
source share
1 answer
 template<class T>struct inner_class_of{using outer_class=T;}; struct Message { struct Binding:inner_class_of<Message> { }; }; template<class T> inner_class_of<T> get_outer_helper(inner_class_of<T>const&); template<class T> using outer_class_of_t = typename decltype(get_outer_helper(std::declval<T>()))::outer_class; 

now outer_class_of_t<Message::Binding> is Message .

I made this a bit of industrial power as it works even if Binding hides outer_class .

You can refuse the helper and rewrite outer_class_of_t=typename T::outer_class if you want.

+5
source share

All Articles