3

auto引入关键字以简化代码。特别是,迭代 stl 容器变得更容易和更好看,而不必std::vector<MyType>::iterator每次想要循环它时都使用丑陋的语法。但是,仍然可以编写代码而不使用autowhich 会做完全相同的事情。

现在(我认为)如果没有 ,您将无法使用某些功能auto,尤其是结构化绑定:

std::tuple<int, int&> f();
auto [x, y] = f();

所以,两个问题:

  1. 我是否正确,如果[x, y]不使用auto(仍然使用结构化绑定)就无法初始化?有没有办法明确地初始化它:*explicit_type* [x, y] = f();
  2. 还需要使用哪些其他功能auto
4

2 回答 2

2

我是否正确,如果[x, y]不使用 auto(仍然使用结构化绑定)就无法初始化?

是的,这是正确的。语法没有指定其他方式,例如可以在此处看到。

还需要使用哪些其他功能auto

一个经典的例子应该是(通用)lambda 表达式:

auto lambda = [](auto&&...) { };

但正如评论中所述,还有其他一些例子。

于 2017-11-05T20:01:53.383 回答
1

cppreference 关于第1点非常清楚,请参阅结构化绑定声明,C++17

attr(optional) cv-auto ref-operator(optional) [ identifier-list ]

哪里cv-auto可能是 cv 限定的类型说明符auto

对于2/我有两个例子:

  1. 已经引用的auto = [](){}; lambda 案例

  2. 另一种是 C++17 Declaring non-type template arguments with auto

一个使用示例是:

template <typename Type, Type value> constexpr Type TConstant = value;

在 C++17 中,可以通过以下方式简化:

template <auto value> constexpr auto TConstant = value;
于 2017-11-05T19:58:04.850 回答