有没有办法找到任意类类型的直接基类(如果有的话)?

时间:2018-05-04 19:03:45

标签: c++ templates reflection

我想创建一个存储对象,我可以在其中设置/获取软件应用程序中各种类型的属性。 (我们只是说该属性是一个字符串。)如果尝试检索某个类型T的属性,而该类型T之前没有存储任何属性,我希望为最基于派生类型返回的属性返回T类。我希望所有这些对存储属性的类类型没有任何特殊要求。

所以基本上,它应该看起来像这样。

class Store
{
  public:
    template <class T> void put(const string& property) { /* MAGIC HERE */ }
    template <class T> string get() const { /* MORE MAGIC */ }
};

class X {};
class Y : public X {};
class Z : public Y {};

int main()
{
    Store store;
    store.put<X>("x");
    store.put<Z>("z");
    cout << store.get<X>() << endl;
    cout << store.get<Y>() << endl;
    cout << store.get<Z>() << endl;
    return 0;
}

输出应如下所示:

x
x
z

这是否可以用C ++实现?用java反射会很容易。

1 个答案:

答案 0 :(得分:1)

&#34;传统&#34;这样做的方法是只为父类(或tuple<>中的类)添加一个类型别名,并使用duck-typing来检索它。

class X {
  // can be resolved automatically with SFINAE, but having an explicit "no parent" 
  // allows to catch mistakes at compile-time more easily.
  using parent_t = void;
};

class Y : public X {
  using parent_t = X;
};

class Z : public Y {
  using parent_t = Y;
};

它是一个相当少量的样板,在我看到它使用的任何地方都很少引起摩擦。

从那时起,在您的情况下,使用Store实施std::unordered_map<std::type_index, std::string>非常简单。

相关问题