如何在C ++中推导出内部类型的外部类型?

时间:2014-06-13 13:19:40

标签: c++ templates metaprogramming

我有很多类暴露了一个名为Binding的内部类型。例如,其中一个可能是:

struct Message
{
    struct Binding
    {
    };
};

我调用了这样的函数apply

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

因为我写了

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

    BindingType binding;
    expr(binding);

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

由于Message在我调用apply的方式上有点多余,我想让编译器推导Message以便我可以编写

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

到目前为止,我被困在这里:

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);
}

有没有办法写/实现MessageTypeFromBinding

显然,这是纯粹的好奇心和美容问题。

1 个答案:

答案 0 :(得分:5)

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;

现在outer_class_of_t<Message::Binding>Message

我做了一点工业强度,因为即使Binding隐藏了outer_class,它仍然有效。

如果您愿意,可以删除助手并重写outer_class_of_t=typename T::outer_class