汽车有什么用

What is the use of auto?

本文关键字:什么 汽车      更新时间:2023-10-16

我知道我们可以像这样使用auto

auto a = 1;
auto b = Foo(1,2);

或者在函数调用中:

auto foo(){
  return Foo(1,2);
}

但是 C++11 还提供了统一的初始化和初始化列表,所以我们可以做到:

Foo a {1,2};
Foo b = {1,2};
Foo foo(){
  return {1,2};
}

那么,如果我们已经有大括号语法,auto有什么用呢?(定义基元类型除外)

我认为当您将auto与好的迭代器一起使用时,可以看到它的最佳用途。比较:

for (std::vector<int>::iterator it = vector.begin(); it != vector.end(); ++it)

自:

for (auto it = vector.begin(); it != vector.end(); ++it)

尽管在 C++11 中,我们有范围可以更好地提供帮助,但迭代器仍然广泛用于您的范围未明确定义或您需要对元素执行操作的情况。

通常,当编译器可以自动推断类型(即要键入的 PITA)时,auto非常有用。

当返回类型未指定时,您需要 auto。例如,std::bind .

using namespace std::placeholders;
int n = 7;
auto f1 = std::bind(f, _2, _1, 42, std::cref(n), n);

auto最适合模板和迭代器。

它不仅可以真正简化语法并提高代码可读性,而且还可以淘汰一些广泛的模板使用。

看看这家伙的页面 - 非常好,切中要害。

简明扼要以下内容:

template <typename BuiltType, typename Builder>
void makeAndProcessObject (const Builder& builder) {
    BuiltType val = builder.makeObject();
    // ...
}

现在有了auto,您可以摆脱模板中的多种类型:

template <typename Builder>
void makeAndProcessObject (const Builder& builder)
{
    auto val = builder.makeObject();
    // ...
}

此外,当您实际调用此函数时,您无需提供任何类型作为模板参数:

MyObjBuilder builder;
makeAndProcessObject(builder);