如果没有 'auto',是否有我无法使用的功能(特别是结构化绑定)?
Are there features (in particular, structured binding) which I can't use without 'auto'?
auto
关键字被引入以简化代码。特别是,迭代 stl 容器变得更容易和更好看,而无需在每次要循环它时都使用丑陋的 std::vector<MyType>::iterator
语法。但是,仍然可以在不使用 auto
的情况下编写代码,这会做完全相同的事情。
现在(我认为)如果没有 auto
,您将无法使用某些功能,尤其是结构化绑定:
std::tuple<int, int&> f();
auto [x, y] = f();
那么,两个问题:
- 如果不使用
auto
(仍在使用结构化绑定)就无法初始化 [x, y]
,我是否正确?有没有办法明确地初始化它:*explicit_type* [x, y] = f();
?
- 还有哪些其他功能需要使用
auto
?
cppreference 关于点 1/ 非常清楚,参见 Structured binding declaration, C++17
attr(optional) cv-auto ref-operator(optional) [ identifier-list ]
其中 cv-auto
可能是 cv 限定的类型说明符 auto
对于2/我有两个例子:
已引用的 auto = [](){};
lambda 案例
一个用法示例是:
template <typename Type, Type value> constexpr Type TConstant = value;
在 C++17 中可以通过以下方式简化:
template <auto value> constexpr auto TConstant = value;
Am I correct that there's no way to initialize [x, y]
without using
auto
(still using structured bindings)?
是的,这是正确的。语法没有指定其他方式,例如 here.
What other features require using auto
?
一个经典的例子应该是(通用的)lambda 表达式:
auto lambda = [](auto&&...) { };
但正如评论中所述,还有一些其他示例。
auto
关键字被引入以简化代码。特别是,迭代 stl 容器变得更容易和更好看,而无需在每次要循环它时都使用丑陋的 std::vector<MyType>::iterator
语法。但是,仍然可以在不使用 auto
的情况下编写代码,这会做完全相同的事情。
现在(我认为)如果没有 auto
,您将无法使用某些功能,尤其是结构化绑定:
std::tuple<int, int&> f();
auto [x, y] = f();
那么,两个问题:
- 如果不使用
auto
(仍在使用结构化绑定)就无法初始化[x, y]
,我是否正确?有没有办法明确地初始化它:*explicit_type* [x, y] = f();
? - 还有哪些其他功能需要使用
auto
?
cppreference 关于点 1/ 非常清楚,参见 Structured binding declaration, C++17
attr(optional) cv-auto ref-operator(optional) [ identifier-list ]
其中 cv-auto
可能是 cv 限定的类型说明符 auto
对于2/我有两个例子:
已引用的
auto = [](){};
lambda 案例
一个用法示例是:
template <typename Type, Type value> constexpr Type TConstant = value;
在 C++17 中可以通过以下方式简化:
template <auto value> constexpr auto TConstant = value;
Am I correct that there's no way to initialize
[x, y]
without usingauto
(still using structured bindings)?
是的,这是正确的。语法没有指定其他方式,例如 here.
What other features require using
auto
?
一个经典的例子应该是(通用的)lambda 表达式:
auto lambda = [](auto&&...) { };
但正如评论中所述,还有一些其他示例。