在C ++中推导继承方法的父类 [英] Deduce parent class of inherited method in C++

查看:106
本文介绍了在C ++中推导继承方法的父类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

采取以下类层次结构:

  template< typename T& 
class Foo {
public:
T fooMethod(){...}
};
class Moo:public Foo< bool> {
...
};

如果我现在在某处写 Moo :: fooMethod 编译器会推导出 Foo< bool> :: fooMethod 。在编译时之前,如何推导 Foo fooMethod 的父类?



动机:编译器不会允许 bool()的 Foo< bool> :: fooMethod Moo :: *)(),因为它在上下文中将是 bool(Foo< bool> :: *)()但是因为我有多个继承,我不知道什么父 fooMethod 将在,它必须被推导。

如果我正确理解问题,可以使用下面的trait来推导出成员函数定义的类:

  template< typename> 
struct member_class_t;

template< typename R,typename C,typename ... A>
struct member_class_t< R(C :: *)(A ...)> {using type = C; };

template< typename R,typename C,typename ... A>
struct member_class_t< R(C :: *)(A ...)const> {using type = C const; };

// ...其他限定词特殊化

template< typename M>
using member_class = typename member_class_t< M> :: type;

之后您可以写

  member_class< decltype(& Moo :: fooMethod)> 

给予 Foo< bool> p>

要更一般地定义 member_class ,您应该考虑 volatile ref - 限定符,总共产生大约12个专业。完整的定义是此处 a>。


Take the following class hierarchy:

template<typename T>
class Foo {
public:
    T fooMethod() { ... }
};
class Moo : public Foo<bool> {
    ...
};

If I now somewhere write Moo::fooMethod the compiler will deduce Foo<bool>::fooMethod. How can I deduce Foo<bool> as parent of fooMethod myself before compile time?

Motivation: the compiler will not allow Foo<bool>::fooMethod to be passed as template parameter for bool (Moo::*)() since it will be of type bool (Foo<bool>::*)() in that context. But since I have multiple inheritance I dont know what parent fooMethod will be in, it must be deduced.

解决方案

If I understand the problem correctly, it is possible to deduce the class a member function is defined in, using the following trait:

template<typename>
struct member_class_t;

template<typename R, typename C, typename... A>
struct member_class_t <R(C::*)(A...)> { using type = C; };

template<typename R, typename C, typename... A>
struct member_class_t <R(C::*)(A...) const> { using type = C const; };

// ...other qualifier specializations

template<typename M>
using member_class = typename member_class_t <M>::type;

after which you can write

member_class<decltype(&Moo::fooMethod)>

giving Foo<bool>.

To define member_class more generally, you should take into account volatile and ref-qualifiers as well, yielding a total of about 12 specializations. A complete definition is here.

这篇关于在C ++中推导继承方法的父类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆