为什么我不能创建自动变量数组?

发布于 2024-11-30 06:16:15 字数 149 浏览 1 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

仅此而已 2024-12-07 06:16:15

auto 将每个大括号括起来的初始值设定项列表推导为 std::initializer_list。 (参见第 7.1.6.4.6 节,包括示例)。
不幸的是,一旦获得数组,甚至无法从 std::initializer_list 初始化 std::array,但您可以使用 std::vector

#include <vector>
#include <array>
#include <initializer_list>

int main()
{
  auto x = {1,2,3};
  std::array<int, 3> foo1 = x; // won't work for whatever reason
  std::vector<int> foo2 = x; // works as expected
  return 0;
}

当然,这违背了你想要做的事情的全部目的。

我尝试编写一个名为 make_array 的解决方案,但必须意识到这永远无法工作,因为 initializer_list 的大小不是其模板参数的一部分,因此您只能实例化每个 T 一个 make_array 模板。这太糟糕了。

template<typename T> 
auto make_array(const std::initializer_list<T>& x) 
     -> std::array<T, x.size()> { } // maaah

好吧,显然你可以使用这里提到的可变模板黑客 如何使用initializer_list初始化成员数组?

auto deduces every brace-enclosed initializer list to a std::initializer_list<T>. (See §7.1.6.4.6 including the example).
Unfortunately you cannot initialize an array or even std::array from a std::initializer_list once you have obtained it, but you can use a std::vector.

#include <vector>
#include <array>
#include <initializer_list>

int main()
{
  auto x = {1,2,3};
  std::array<int, 3> foo1 = x; // won't work for whatever reason
  std::vector<int> foo2 = x; // works as expected
  return 0;
}

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 an initializer_list isn't part of its template arguments and so you only instantiate one make_array template for each T. This sucks.

template<typename T> 
auto make_array(const std::initializer_list<T>& x) 
     -> std::array<T, x.size()> { } // maaah

Well, apparently you can go for the variadic-template hack mentioned here How do I initialize a member array with an initializer_list?

暖阳 2024-12-07 06:16:15

因为 {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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文