【问题标题】:Deduce parent class of inherited method in C++在 C++ 中推断继承方法的父类
【发布时间】:2014-06-21 05:09:56
【问题描述】:

采用以下类层次结构:

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

如果我现在在某处写Moo::fooMethod,编译器将推导出Foo&lt;bool&gt;::fooMethod。我如何在编译之前将Foo&lt;bool&gt; 自己推断为fooMethod 的父级?

动机:编译器不允许将Foo&lt;bool&gt;::fooMethod 作为bool (Moo::*)() 的模板参数传递,因为在该上下文中它将是bool (Foo&lt;bool&gt;::*)() 类型。但是由于我有多重继承,我不知道fooMethod会在哪个父级,所以必须推导出来。

【问题讨论】:

标签: c++ inheritance


【解决方案1】:

如果我正确理解了这个问题,可以使用以下特征推断出定义成员函数的类:

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;

之后你可以写

member_class<decltype(&Moo::fooMethod)>

Foo&lt;bool&gt;

要更一般地定义member_class,您还应该考虑volatileref-限定符,总共产生大约12 个专业化。完整的定义是here

【讨论】:

  • 这个简单的分解正是我想要的,太棒了! :) 非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-06
  • 1970-01-01
  • 1970-01-01
  • 2015-07-04
相关资源
最近更新 更多