如何在C++中推导内部类型的外部类型
How can I deduce the outer type of an inner type in C++?
我有许多类公开了一个名为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
。
相关文章:
- 来自 Android 应用程序内部的 boost 类型的 boost::wrapexcept<boost::system::system_error> 的未捕获异常
- 嵌套模板函数采用 2 个具有相同内部类型的容器
- 返回给定 SEXP 的子集,而无需知道实际的内部数据类型
- 如何理解c++中在命名空间内部定义的枚举类型enum
- 在变量名后声明带有 () 的非内部类型与不使用变量名的行为不同。即 std::map<int,char>x(); - 这是怎么回事?
- C++:在"try"外部创建的类型会导致错误,但在内部不会
- 如何在QTScript中将QLIST内部的QMAP注册为元素类型
- 如何通过从变量中获取类型来访问内部 typedef
- 是一个被认为是不同类型的班级内部的正向声明
- 如何从对象内部的 typedef 获取模板参数类型
- 如何使用 C 的内部 C++ 类类型?
- 具有模板类型内部功能的不同操作的NOExcept
- 在C++中,当两个向量类型不同时,如何将值存储到向量内部的向量中
- 如何将负数转换为更广泛的类型在内部工作
- 如何为模板的内部类型专用化类
- 从函数内部推断函数返回类型
- C 名称当前类型内部模板
- 从内部类型参数推断外部类型
- 从 lambda 内部返回 C++11 中的 lambda 类型(平面映射函数)
- 在 CUDA 中使用内部类型转换的奇怪错误