【问题标题】:How to determine the outer class of a nested class structure in C++如何在 C++ 中确定嵌套类结构的外部类
【发布时间】:2016-11-21 17:05:57
【问题描述】:

想象一下,你有一个像下面这样的嵌套类结构:

struct A
{
    struct B
    {
        struct C{};
    };
};

如果你给了一个 C 的实例,就叫 c 之类的

A::B::C c;

可以推断

  • 最外层的类(这里是 A)
  • 层次结构中的下一个类(此处为 B)
  • 嵌套数(此处为 2)

通过模板、编译时递归和模板专业化技术?我尝试了以下几个模板:

template<typename Outer , typename Inner , typename Outer::Inner>
struct nested
{
    typedef typename Outer::Innter type;
};

但是如您所见,我无法对 B 和 C 的逐步推导进行递归。您有什么建议吗?

【问题讨论】:

  • 我很想知道您通过了解嵌套结构来解决什么问题
  • 简单地说,它是一个冗长的算法。
  • 你能解释一下否决票吗?我想了解我的错误并改进我的帖子!
  • 听起来像是XY Problem 的情况。你希望通过这些内部类实现什么?可能有更简单的方法。
  • 我唯一能想到的就是让你的类继承自一个存储信息的模板类。一个简单的解决方案可能是godbolt.org/g/jWpa72 - 您当然可以将其扩展到例如除了作为父母的原始人

标签: c++ templates inner-classes type-deduction


【解决方案1】:

您可以创建一个您手动为其提供的特征:

struct A
{
    struct B
    {
        struct C{};
    };
};

template <typename T> struct outter {
    static constexpr const std::size_t count = 0u;
};

template <> struct outter<A::B::C>
{
    using type = A::B;
    static constexpr const std::size_t count = 2u;
};

template <> struct outter<A::B>
{
    using type = A;
    static constexpr const std::size_t count = 1u;
};

【讨论】:

  • 对于我必须处理的少数情况,这可能是一个可能的解决方案。非常感谢这个建议。
【解决方案2】:

没有。就编译器而言,AA::BA::B::C 是独立的无关类(名称查找/范围除外)。

如果您知道您的实现type_info::name() 的格式,您也许可以在运行时做一些事情。

【讨论】:

    猜你喜欢
    • 2015-05-12
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-14
    • 1970-01-01
    • 2019-07-29
    相关资源
    最近更新 更多