Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
591 views
in Technique[技术] by (71.8m points)

templates - How can I deduce the outer type of an inner type in C++?

I have many classes exposing an inner type named Binding. For instance, one of them could be:

struct Message
{
    struct Binding
    {
    };
};

I invoke a function apply like this:

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

for 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 is a bit redundant in the way I invoke apply, I would like to make the compiler deduce Message so I can write

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

So far, I am 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, i.e. Message
    typedef typename MessageTypeFromBinding< BindingType >::Type MessageType;

    apply(MessageUtil::typeId< MessageType >(), binding);
}

Is there a way to write/achieve MessageTypeFromBinding?

Obviously, that's pure curiosity and cosmetic concerns.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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 it a bit industrial strength, as it works even if Binding hides outer_class.

You can drop helper and rewrite outer_class_of_t=typename T::outer_class if you prefer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...