2011-03-29 107 views
6

我想創建一個數組:C++初始化列表和可變參數模板

template < typename T, typename ... A > struct a { 
    T x [1 + sizeof... (A)]; 
    a() = default; 
    a (T && t, A && ... y) : x { t, y... } {} 
}; 

int main() { 
    a < int, int > p { 1, 1 }; // ok 
    a < a < int, int >, a < int, int > > q { { 1, 1 }, { 3, 3 } }; // error: bad array initializer 
} 

爲什麼不把它編譯? (用g ++ 4.6測試)

+1

爲什麼這麼複雜o0 – orlp 2011-03-29 15:41:44

+0

它拋出了什麼錯誤? – ChrisE 2011-03-29 15:59:50

+3

我*認爲*這是一個錯誤。 – GManNickG 2011-03-29 16:34:39

回答

2

我很確定這是一個bug。可以使用{}來代替()爲構造函數提供參數。因此,您的代碼應該沒問題:

int main() 
{ 
    // this is fine, calls constructor with {1, 1}, {3, 3} 
    a<a<int, int>, a<int, int>> q({ 1, 1 }, { 3, 3 }); 

    // which in turn needs to construct a T from {1, 1}, 
    // which is fine because that's the same as: 
    a<int, int>{1, 1}; // same as: a<int, int>(1, 1); 

    // and that's trivially okay (and tested in your code) 

    // we do likewise with A..., which is the same as above 
    // except with {3, 3}; and the values don't affect it 
} 

所以整件事情應該沒問題。