2015-09-10 72 views
1

的代码首先片段:派生类:使用基类成员在初始化列表

struct Base 
{ 
    int x{}; 
}; 

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

    int y; 
}; 

int main() 
{ 
    Derived d; 
} 

上编译罚款:

  • gcc(6.0.0)
  • clang(3.8.0) (Visual Studio 2013 Update 4,18.00.31101)

的代码片段二:

#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和铛,我需要指定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编译会太):

问题:哪个编译器是正确的?什么标准说这个?

由于

+1

在Visual Studio中禁用“语言扩展”('/ Za')使其拒绝您的第二个片段。经常使用的经验法则:如果有疑问,VC++是错误的。 – molbdnilo

+0

@molbdnilo,谢谢 – grisha

回答

2

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

更改为简单this->x也适用,所以VC++在这里是错误的。

相关问题