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

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

本文关键字:类型 内部 外部 C++      更新时间:2023-10-16

我有许多类公开了一个名为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的方法?

很明显,这纯粹是出于好奇和外表的考虑。

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;

现在CCD_ 7是CCD_。

我让它有点工业实力,因为即使Binding隐藏了outer_class,它也能工作。

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