【问题标题】:Derived class: using Base class member in initializer list派生类:在初始化列表中使用基类成员
【发布时间】:2015-09-10 11:04:01
【问题描述】:

代码的第一个sn-p:

struct Base
{
    int x{};
};

struct Derived :
    Base
{
    Derived()
        : y{x}
    {
    }

    int y;
};

int main()
{
    Derived d;
}

编译正常:

  • gcc (6.0.0)
  • clang (3.8.0)
  • vc++(Visual Studio 2013 更新 4,18.00.31101)

第二个sn-p代码:

#include <type_traits>

template<int N>
struct Base
{
    int x = N;
};

static const int When0 = -1;

template<int N>
struct Derived :
    std::conditional<N == 0,
        Base<When0>,
        Base<N>>::type
{
    Derived()
        : y{x}
    {
    }

    int y;
};

int main()
{
    Derived<0> d;
}

编译正常:

不会编译:

要修复 gcc 和 clang,我需要指定 x 的类:

#include <type_traits>

template<int N>
struct Base
{
    int x = N;
};

static const int When0 = -1;

template<int N>
struct Derived :
    std::conditional<N == 0,
        Base<When0>,
        Base<N>>::type
{
    using base_t = typename std::conditional<N == 0,
        Base<When0>,
        Base<N>>::type;

    Derived()
        : y{base_t::x}
    {
    }

    int y;
};

int main()
{
    Derived<0> d;
}

看(vc也会编译):

问题:哪个编译器是正确的?对此有何标准?

谢谢

【问题讨论】:

  • 在 Visual Studio 中禁用“语言扩展”(/Za) 会使其拒绝您的第二个 sn-p。经常使用的经验法则:当有疑问时,VC++ 是错误的。

标签: c++ visual-c++ gcc clang


【解决方案1】:

这是从模板派生类访问基类(非依赖)成员的标准问题。见this FAQ entry

将其更改为简单的 this-&gt;x 也可以,因此 VC++ 在这里是错误的。

【讨论】:

    猜你喜欢
    • 2010-11-10
    • 1970-01-01
    • 2019-01-25
    • 2017-12-13
    • 2017-08-30
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多