“auto”关键字的要点是什么? [英] What is the point of the 'auto' keyword?
问题描述
所以我理解在C#中使用 var
是有意义的,因为你有匿名类型是编译器派生的。 C ++似乎没有这个功能(除非我错了),那么有一个 auto
关键字的意义是什么?
(这是很酷,不像C#, auto
适用于成员/全局变量,这是很酷我猜,但似乎不够证明其存在)。
auto
它归结为通用编程和保存程序员一些打字。
例如,考虑这个。您要输入:
std :: unique_ptr< name :: long_type :: goes_here> g =
std :: make_unique< name :: long_type :: goes_here>(1,2,3,4)
或:
auto g = std :: make_unique< name :: long_type :: goes_here> 1,2,3,4)
是的,他们都很长,但我们知道返回类型并再次指定它是一个有点麻烦的类型。这也适用于迭代器:
for(auto i = vec.begin(); ...)
vs:
for(std :: vector< type> :: iterator i = vev.begin(); ...)
它在泛型编程中的使用也是为了弄清楚函数的返回类型,或者如果你在做一些不知道类型的通用算法。
<例如,考虑一个非常基本的例子。
template< typename T,typename U>
auto add(T t,U u) - > decltype(t + u){
return t + u;
}
这允许编译器找出add操作的类型,试图找出自己。请注意,在C ++ 14中,您可以省略尾随返回类型。它在通用编程中的使用也不止于此。如果我们想使用任何类型的容器作为算法的包装函数,我们可以使用 auto
来帮助我们。例如:
模板< class Cont>
void my_sort(Cont&& cont){
using std :: begin;
auto first = begin(std :: forward< Cont>(cont));
//使用这里的迭代器
}
++ 14),auto可以用于生成多态lambda语句,如:
a + 4; }
这也很有用。
So I understand using var
in C# makes sense because you have anonymous types that are compiler derived. C++ doesn't seem to have this feature (unless I'm wrong), so what is the point of having an auto
keyword?
(It is kinda cool that unlike C#, auto
does work for member/global variables, which is cool I guess, but doesn't seem enough to justify its existence).
auto
has a lot of uses when it comes down to both generic programming and to save the programmer some typing.
For example, consider this. Would you rather type out:
std::unique_ptr<name::long_type::goes_here> g =
std::make_unique<name::long_type::goes_here>(1,2,3,4)
or:
auto g = std::make_unique<name::long_type::goes_here>(1,2,3,4)
Yes, they're both long but we know the return type and specifying it again is a bit cumbersome to type. This also goes for iterators:
for(auto i = vec.begin(); ...)
vs:
for(std::vector<type>::iterator i = vev.begin(); ...)
Its use in generic programming is also to figure out the return type of a function or if you're doing some generic algorithms where you don't know the type.
For example, consider a very basic example.
template<typename T, typename U>
auto add(T t, U u) -> decltype(t + u) {
return t + u;
}
This allows the compiler to figure out the type of the add operation rather than us trying to figure it out ourselves. Note that in C++14 you can omit the trailing return type. Its uses in generic programming don't stop there either. If we wanted to work with any type of container as a wrapper function for algorithms we could use auto
to help us with it. For example:
template<class Cont>
void my_sort(Cont&& cont) {
using std::begin;
auto first = begin(std::forward<Cont>(cont));
// work with the iterators here
}
In the future (C++14), auto can be used to make polymorphic lambdas as well such as:
[](auto a) { return a + 4; }
Which can be useful as well.
这篇关于“auto”关键字的要点是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!