【问题标题】:Create instance of derrived inner class in base class [duplicate]在基类中创建派生内部类的实例[重复]
【发布时间】:2021-02-28 03:31:49
【问题描述】:

有没有办法在基类上创建一个在派生类中定义的内部类的实例?见下文。

template<typename D>
struct Base {
  D::Data data; // MSVC 2019 gives me compilation errors.
};

struct Derrived : Base<Derrived> {
    struct Data {
      bool b = false;
      int  i = 0;
    };
};

【问题讨论】:

  • 这能回答你的问题吗? C++ static polymorphism (CRTP) and using typedefs from derived classes这个问题问的是typedef而不是嵌套类型,但我相信限制是一样的。
  • 链接的问题没有解决我的问题,因为一些细节有很大不同。在链接的问题中,模板参数是传入的,因此可以在类定义之前定义它,而在我的问题中,它是一个内部类,无法预先定义。

标签: c++


【解决方案1】:

不,这不起作用,原因有两个:

  1. D::Data 的类型依赖D 的类型,这是一个模板参数,因此这可能会导致编译器产生歧义。一些编译器会对此发出警告,例如:

    prog.cpp:6:3: error: need ‘typename’ before ‘D::Data’ because ‘D’ is a dependent scope
       D::Data data;
    ^
    

    所以,D::Data 需要以typename 为前缀,让编译器知道Data 实际上是一个类型而不是其他东西(即常量、成员字段等),例如:

    template<typename D>
    struct Base {
      typename D::Data data;
    };
    
  2. 然而,即使修复了这个问题,代码仍然无法工作,因为在 D 模板参数的上下文中,Derrived 是一个不完整类型,因为它还没有在实例化Base&lt;Derrived&gt; 时已完全定义:

    prog.cpp: In instantiation of ‘struct Base<Derrived>’:
    prog.cpp:9:19:   required from here
    prog.cpp:6:20: error: invalid use of incomplete type ‘struct Derrived’
       typename D::Data data;
                        ^~~~
    prog.cpp:9:8: note: forward declaration of ‘struct Derrived’
     struct Derrived : Base<Derrived> {
            ^~~~~~~~
    

    因此,编译器将无法将 D::Data 解析为 Derrived::Data,甚至还没有定义。

【讨论】:

    猜你喜欢
    • 2014-09-29
    • 1970-01-01
    • 1970-01-01
    • 2023-02-22
    • 2013-02-12
    • 2014-08-21
    • 2011-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多