Alternative function syntax difference
Asked Answered
C

3

7

What's the difference between these two functions?

auto func(int a, int b) -> int;

int func(int a, int b);
Compendious answered 30/12, 2012 at 2:8 Comment(0)
P
10

Other than the notation, there isn't any difference in the above case. The alternative function declaration syntax become important when you want to refer to one or more of the arguments to determine the return type of the function. For example:

template <typename S, typename T>
auto multiply(S const& s, T const& t) -> decltype(s * t);

(yes, it is a silly example)

Pol answered 30/12, 2012 at 2:13 Comment(7)
I never understood why a compiler can't handle the same with the old syntax, like: template <typename S, typename T> decltype(s * t) multiply(S const& s, T const& t); Do you know why?Githens
@leemes: It is possible that compilers could do the same with the old style syntax but C++ consistently follows the rule that no name is visible before it is declared. Whether this rule is a good rule to have is a separate question but the consistency helps.Olympie
@DietmarKühl But as far as I know I can define a class with two methods and call the second within the first being implemented inline. Like class A { void a() { b(); } void b(); }; So I thought that this is not a very strict design rule.Githens
@billz: Of course, the lambda rules and the trailing return went somewhat hand in hand: If there were no trailing returns for function something different would be used for lambdas as well. I seem to recall that both notations were developed pretty much together.Olympie
@leemes: Yes, that is correct but it doesn't break the rule: The member functions defined within a class definition are treated as if they are defined outside the class definition, immediately following the class definition. The member definitions inside the class are just a short-hand (although I'm not quite sure how this works with friend functions inside a class template as these cannot be defined outside the class definition).Olympie
@DietmarKühl Ok from this point of view, this rule holds. However, having the old syntax for decltype return types would have been a nice feature... But one cannot have everything ;)Githens
+1: silly example, perhaps, but a very precise one, none the less.Sedimentary
C
5

There is no useful difference between these two declarations; both functions return an int.

C++11's trailing return type is useful with functions with template arguments, where the return type is not known until compile-time, such as in this question: How do I properly write trailing return type?

Connubial answered 30/12, 2012 at 2:13 Comment(0)
A
2

They use different syntax and only one of them is valid in C++ versions prior to C++11. Other than that there are no differences between the two function declarations that you've shown in your question.

Antioch answered 30/12, 2012 at 2:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.