mis*_*why 5 c++ templates metaprogramming
我有很多类暴露一个名为的内部类型Binding.例如,其中一个可能是:
struct Message
{
struct Binding
{
};
};
Run Code Online (Sandbox Code Playgroud)
我调用这样的函数apply:
apply< Message >([](Message::Binding& x)
{
// setup binding fields
});
Run Code Online (Sandbox Code Playgroud)
因为我写了
template <class TMessage, class TBindingExpression>
void apply(const TBindingExpression& expr)
{
typedef typename TMessage::Binding BindingType;
BindingType binding;
expr(binding);
apply(MessageUtil::typeId< TMessage >(), binding);
}
Run Code Online (Sandbox Code Playgroud)
因为Message我调用的方式有点多余,所以我apply想让编译器推断出来Message以便我可以编写
apply([](Message::Binding x)
{
//...
});
Run Code Online (Sandbox Code Playgroud)
到目前为止,我被困在这里:
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);
}
Run Code Online (Sandbox Code Playgroud)
有没有办法写/实现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;
Run Code Online (Sandbox Code Playgroud)
现在outer_class_of_t<Message::Binding>是Message.
我做了一点工业实力,因为即使Binding隐藏它也能工作outer_class.
outer_class_of_t=typename T::outer_class如果您愿意,可以删除助手并重写.
| 归档时间: |
|
| 查看次数: |
418 次 |
| 最近记录: |