【问题标题】:Why can't a typedef type be used to declare its parent class' ctors? [duplicate]为什么不能使用 typedef 类型来声明其父类的 ctor? [复制]
【发布时间】:2020-08-19 16:02:48
【问题描述】:
template<typename>
struct A
{
    int n;

    A(bool)
    {}
};

template<typename>
struct B
{
    struct C : A<B>
    {
        using Base = A<B>;

        using A<B>::A; // ok
        using Base::n; // ok

        // error: dependent using declaration resolved to type without 'typename'
        using Base::A;
    };

    C get() const
    {
        return C(true);
    }
};

int main()
{
    auto b = B<int>();
    b.get();
}

代码中描述了错误。

为什么不能使用 typedef 类型来声明其父类的 ctor?

【问题讨论】:

  • 注意:适用于 GCC 9.3 和 MSVC v19.24。在 Clang 10.0.0 中失败(添加 typename 关键字可以解决该问题,但 Clang 有 GCC 没有的其他问题)。

标签: c++ inheritance typedef using-directives using-declaration


【解决方案1】:

reported 之前的类似行为可能是 Clang 错误:[错误 23107] 模板上的构造函数继承无法正常工作

Richard Smith 对此报告的评论:

C++ 委员会已经讨论过这个案例,但并不打算使用那种语法 有效。请改用using myBase::myBase; 来声明继承构造函数。

所以,你应该写using Base::Base; 而不是using Base::A;。完成此修复后,您的代码将使用 Clang 进行编译。

【讨论】:

【解决方案2】:

正如其他人评论的那样,您的代码在最新的 GCC 和 MSVC 上编译没有问题。

您的问题似乎发生在 Clang 上。

该标准对析构函数有类似的命名问题 (source):

在以下形式的限定 ID 中:

[...] 类型名称::~类型名称

在与第一个相同的范围内查找第二个类型名称。

struct C {
  typedef int I;
};
typedef int I1, I2;
extern int* p;
extern int* q;
p->C::I::~I();      // I is looked up in the scope of C
q->I1::~I2();       // I2 is looked up in the scope of the postfix-expression

struct A {
  ~A();
};
typedef A AB;
int main() {
  AB* p;
  p->AB::~AB();     // explicitly calls the destructor for A
}

但我找不到任何与构造函数相关的明确内容。我认为行为应该是相同的,但只有对标准更有经验的人才能确认。

有趣的是,如果您将 A 类设为不是模板,它也适用于 Clang:

struct A
{
    A(bool) {}
};

template<typename>
struct B
{
    struct C : A
    {
        using Base = A;
        using Base::A;
    };
//...

所以这可能是一个 Clang 错误?

你可以做的一件事是使用Base的构造函数:Base::Base

struct C : A<B>
{
    using Base = A<B>;
    using Base::Base;
};

【讨论】:

    猜你喜欢
    • 2011-10-12
    • 2012-05-07
    • 1970-01-01
    • 2013-05-17
    • 2011-04-16
    • 1970-01-01
    • 2018-07-16
    • 2016-07-03
    • 1970-01-01
    相关资源
    最近更新 更多