c++ - 如何在继承级别为容器类做可见的嵌套类?

标签 c++ templates inheritance inner-classes

我有一些模板类

template <typename T> class Base { };

我尝试从Base继承Derived类,并使用嵌套DerivedInternal类作为Base 的通用参数。

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

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

是否可以通过将 Internal 类保留为 Derived 的嵌套来解决我的问题? 如果可能的话 - 如何实现?

最佳答案

你可以!

( similar question )

我认为这行不通。为了定义Derived,您首先需要知道基类(“它必须是一个完整的类型”);要将模板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;

关于c++ - 如何在继承级别为容器类做可见的嵌套类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63225204/

相关文章:

c++ - 为指针赋值

android - "module “QtQuick” 未安装”(安卓移植)

c++ - 是否可以在 C++ 中提取容器模板类?

c++ - 获取类模板成员的函数类型?

java - jUnit 忽略来自基类的@Test 方法

c++ - 包装数据结构

c++ - 带有指针的循环不起作用

c++ - 指针类型是文字类型吗?

c++ - 模板实例化期间函数定义的顺序

ruby - 通过继承的 Rspec 常量