在派生构造函数初始化列表中初始化模板
Initialise template within derived constructor initialisation list
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
是的,您只需要一副额外的牙套:
struct Foo: std::array<int, 2> {
Foo() {}
Foo(const int & x, const int & y) : std::array<int, 2> {{ x, y }} {}
^ ^
};
对于 VC++ 编译器,您需要一对圆括号而不是大括号:
struct Foo : std::array<int, 2> {
Foo() {}
Foo(const int & x, const int & y) : std::array<int, 2>({ x, y }) {}
^ ^
};
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
是的,您只需要一副额外的牙套:
struct Foo: std::array<int, 2> {
Foo() {}
Foo(const int & x, const int & y) : std::array<int, 2> {{ x, y }} {}
^ ^
};
对于 VC++ 编译器,您需要一对圆括号而不是大括号:
struct Foo : std::array<int, 2> {
Foo() {}
Foo(const int & x, const int & y) : std::array<int, 2>({ x, y }) {}
^ ^
};