如何在C ++中推导出一个内部类型的外部类型? [英] How can I deduce the outer type of an inner type in C++?
问题描述
我有很多类暴露一个名为 Binding
的内部类型。例如,其中一个可以是:
I have many classes exposing an inner type named Binding
. For instance, one of them could be:
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);
}
由于讯息
在我调用 apply
的方式有点冗余,我想让编译器推导消息
所以我可以写
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);
}
有一种方法可以写/实现 MessageTypeFromBinding
?
Is there a way to write/achieve MessageTypeFromBinding
?
显然,这是纯粹的好奇心和化妆品的问题。
Obviously, that's pure curiosity and cosmetic concerns.
推荐答案
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>
我有点工业实力,因为即使绑定隐藏
outer_class
。
I made it a bit industrial strength, as it works even if Binding
hides outer_class
.
您可以放置帮助程序并重写 outer_class_of_t = typename T :: outer_class
(如果您愿意)。
You can drop helper and rewrite outer_class_of_t=typename T::outer_class
if you prefer.
这篇关于如何在C ++中推导出一个内部类型的外部类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!