【问题标题】:How to do visible nested-class for container-class in inheritance level?如何在继承级别为容器类做可见的嵌套类?
【发布时间】:2020-08-03 07:15:45
【问题描述】:

我有一些模板类

template <typename T> class Base { };

我试图从 Base 继承 Derived 类,并使用嵌套在 Derived 中的 Internal 类作为Base 的通用参数。

class Derived : Base<Internal> {
public: class Internal { };
}

但编译器在 Base 中看不到 Internal。

是否可以通过将 Internal 类保持为 Derived 的嵌套来解决我的问题? 如果可能的话 - 怎么做?

【问题讨论】:

  • 我担心这是否可行,但您必须使用范围:Derived::Internal。
  • @Scheff 我也试过这个变种,结果相同,内部仍然不可见。
  • 我怀疑可以使用嵌套类。前向声明也不是一种选择。也许更复杂的事情......

标签: c++ templates inheritance inner-classes


【解决方案1】:

你可以!不

(similar question)

我认为这行不通。为了定义类Derived,你首先需要知道基类(“它必须是一个完整的类型”);要将 template Base 实例化为您需要有类型的类。 Inner 然而只是Derived 的“内部”类型;这是定义的一部分。


Definition of Derived  ---needs---> Base<Derived::Inner>
          ^                               |
          |----------needs----------------|

即使是间接也无济于事:

template<typename T>
class Base {};

template<template<class> class X, typename T>
struct UseInner : public X<typename T::Inner> {};

class Derived : UseInner<Base, Derived>
{
    public: class Inner {};
};

与此相反,CRTP 有效,因为模板参数可以是 不完整 类型(“无需访问内部”)。

包装在模板中不起作用:

template<typename T>
class Base {};

template<template<class>class X>
struct Wrap
{
    struct Derived : X<typename Derived::Inner> {
        struct Inner {};
    };
};

using RealDerived = typename Wrap<Base>::Derived;

【讨论】:

    猜你喜欢
    • 2012-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多