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
156 views
in Technique[技术] by (71.8m points)

c++ - What is the meaning of auto main()->int?

I happened to come across the below code snippet in a video on C++11, where the author uses

auto main()->int

I didn't understand this. I tried to compile in g++ using -std=c++11 and it works. Can somebody explain to me what is going on here? I tried to search using "auto main()->int" but didn't find any help.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

C++11 introduced a notation for trailing return types: If a function declaration is introduced with auto, the return type will be specified after the parameters and a -> sequence. That is, all that does is to declare main() to return int.

The significance of trailing return types is primarily for function template where it is now possible to use parameters to the function together with decltype() to determine the return type. For example:

template <typename M, typename N>
auto multiply(M const& m, N const& n) -> decltype(m * n);

This declares the function multiply() to return the type produced by m * n. Putting the use of decltype() in front of multiply() would be invalid because m and n are not, yet, declared.

Although it is primarily useful for function template, the same notation can also be used for other function. With C++14 the trailing return type can even be omitted when the function is introduced with auto under some conditions.


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

...