我如何初始化与initializer_list的成员数组? [英] How do I initialize a member array with an initializer_list?
问题描述
我得到了的C ++ 0x加快和测试的东西出来与G ++ 4.6
我只是尝试了以下code,认为它会工作,但它不会编译。我得到的错误:
不兼容的类型中分配'的std :: initializer_list< const int的>'到'const int的[2]
结构美孚
{
INT常量数据[2]; 美孚(的std :: initializer_list< INT常量>&安培; INI)
:数据(INI)
{}
};富F = {1,3};
您可以使用可变参数模板的构造函数,而不是一个初始化列表构造器:
结构foo的{
INT X [2];
模板< typename的... T>
美孚(T ... TS):X {TS ...} {//注意使用大括号初始化列表中
}
};诠释主(){
富F1(1,2); // 好
富F2 {1,2}; //也OK
富F3(42); // 好; X [1]零初始化
富F4(1,2,3); //错误:太多的初始化
富F5(3.14); //错误:缩小转换不允许
富F6(富); //错误:没有从为const char *转换为int
}
编辑:如果你生活中可以没有常量性,的另一种方法是跳过初始化并填写函数体数组:
结构foo的{
INT X [2]; //或std ::阵列< INT,2 - ; X;
美孚(的std :: initializer_list< INT> IL){
性病::复制(il.begin(),il.end(),X);
//或std ::复制(il.begin(),il.end(),x.begin());
//或x.fill(il.begin());
}
}
这样的话,虽然,你失去了编译时边界检查,前者解决方案提供。
I'm getting up to speed with C++0x, and testing things out with g++ 4.6
I just tried the following code, thinking it would work, but it doesn't compile. I get the error:
incompatible types in assignment of ‘std::initializer_list<const int>’ to ‘const int [2]’
struct Foo
{
int const data[2];
Foo(std::initializer_list<int const>& ini)
: data(ini)
{}
};
Foo f = {1,3};
You can use a variadic template constructor instead of an initializer list constructor:
struct foo {
int x[2];
template <typename... T>
foo(T... ts) : x{ts...} { // note the use of brace-init-list
}
};
int main() {
foo f1(1,2); // OK
foo f2{1,2}; // Also OK
foo f3(42); // OK; x[1] zero-initialized
foo f4(1,2,3); // Error: too many initializers
foo f5(3.14); // Error: narrowing conversion not allowed
foo f6("foo"); // Error: no conversion from const char* to int
}
EDIT: If you can live without constness, another way would be to skip initialization and fill the array in the function body:
struct foo {
int x[2]; // or std::array<int, 2> x;
foo(std::initializer_list<int> il) {
std::copy(il.begin(), il.end(), x);
// or std::copy(il.begin(), il.end(), x.begin());
// or x.fill(il.begin());
}
}
This way, though, you lose the compile-time bounds checking that the former solution provides.
这篇关于我如何初始化与initializer_list的成员数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!