Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

c++ - What is the point of the 'auto' keyword?

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...