2015-09-10 100 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++在這裏是錯誤的。

相關問題