2016-04-08 122 views
0

Foo繼承std::array<int, 2>。可以在Foo的構造函數的初始化列表中填充數組嗎?在派生構造函數初始化列表中初始化模板

如果是這樣,下面的語法將是一個有效的替代方案嗎?

// Foo is always an array of 2 ints 
struct Foo: std::array<int, 2> 
{ 
    Foo() {} 
    Foo(const int & x, const int & y) : std::array<int, 2> { x, y } {} 
} 

我嘗試添加一個額外的一對大括號,這對G ++的作品,但不是在VC2015編譯:

#include <array> 
#include <iostream> 

struct Foo : std::array<int, 2> 
{ 
    Foo() {} 
    Foo(const int & x, const int & y) : std::array<int, 2> {{ x, y }} {} 
}; 

int main() 
{ 
    Foo foo(5, 12); 

    std::cout << foo[0] << std::endl; 
    std::cout << foo[1] << std::endl; 

    system("PAUSE"); 
} 

,得到了以下錯誤:https://i.gyazo.com/4dcbb68d619085461ef814a01b8c7d02.png

+1

爲什麼'Foo'從'的std :: array'繼承? –

+0

在我的應用程序中,它將是一個帶有GetX()SetY()函數等的點/矢量類。對我來說,這比使用x,y,z數據成員的結構更有意義,因爲它允許我爲每個維度移除重複的代碼。 –

+1

這當然取決於你如何設計的東西。但是我會說繼承不是大多數作業的最佳工具(http://blog.codinghorror.com/inherits-nothing/,而且,與C#不同的是,大多數C++標準庫並不是真的被設計爲從)。雖然你可以繼承'std :: array',但是它沒有'virtual'函數,這意味着你幾乎不會通過'std :: array'指針或引用與你的'Foo'交互;但這沒關係,因爲'std :: array'的析構函數是非虛擬的,所以當你銷燬對象時你需要知道你真的有'Foo'。 –

回答

2

是的,你只需要一對額外的牙套:

struct Foo: std::array<int, 2> { 
    Foo() {} 
    Foo(const int & x, const int & y) : std::array<int, 2> {{ x, y }} {} 
                 ^ ^
}; 

Live Demo

對於VC++編譯器,你需要一對括號,而不是括號:

struct Foo : std::array<int, 2> { 
    Foo() {} 
    Foo(const int & x, const int & y) : std::array<int, 2>({ x, y }) {} 
                 ^ ^
}; 
+0

不幸的是,這是行不通的;請看我編輯的問題。 編輯:在VS2015 –

+0

謝謝!您的最新編輯工作正常。標記爲已解決。 –