2016-04-08 115 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

谢谢!您的最新编辑工作正常。标记为已解决。 –

相关问题