为什么我不能创建自动变量数组?
在 C++0x(哦!请阅读 C++11)中,我们有自动类型推断。让我好奇的一件事是我无法创建自动变量数组。例如:
auto A[] = {1, 2, 3, 4}; // Error!
有什么想法为什么这可能被禁止吗?
In C++0x (ohh! read C++11), we have automatic type inference. One thing which made me curious was that I can't create an array of auto variables. For example:
auto A[] = {1, 2, 3, 4}; // Error!
Any ideas why this might have been disallowed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
auto
将每个大括号括起来的初始值设定项列表推导为std::initializer_list
。 (参见第 7.1.6.4.6 节,包括示例)。不幸的是,一旦获得数组,甚至无法从
std::initializer_list
初始化std::array
,但您可以使用std::vector
。当然,这违背了你想要做的事情的全部目的。
我尝试编写一个名为
make_array
的解决方案,但必须意识到这永远无法工作,因为initializer_list
的大小不是其模板参数的一部分,因此您只能实例化每个T
一个make_array
模板。这太糟糕了。好吧,显然你可以使用这里提到的可变模板黑客 如何使用initializer_list初始化成员数组?
auto
deduces every brace-enclosed initializer list to astd::initializer_list<T>
. (See §7.1.6.4.6 including the example).Unfortunately you cannot initialize an array or even
std::array
from astd::initializer_list
once you have obtained it, but you can use astd::vector
.Of course this defeats the whole purpose of what you are trying to do.
I tried writing a work around called
make_array
but had to realize that this cannot ever work as the size of aninitializer_list
isn't part of its template arguments and so you only instantiate onemake_array
template for eachT
. This sucks.Well, apparently you can go for the variadic-template hack mentioned here How do I initialize a member array with an initializer_list?
因为
{1, 2, 3, 4}
纯粹是一个语法结构 - 它不是一个表达式,也没有类型。因此,auto
无法从中推断出其类型。Because
{1, 2, 3, 4}
is purely a syntactic construct- it is not an expression and does not have a type. Therefore,auto
cannot deduce its type from it.