8

lately I've seen some code with functions labeled like this:

auto Function(...) -> BOOL

Is there some difference between using just

BOOL Function(...)

The first one looks nicer to me though, maybe I'm just weird, so is it just visual, or it has some other benefits?

Martin Prince
  • 139
  • 1
  • 5

2 Answers2

7

The statement auto Function(...) -> some_type is used when you need type deduction of the arguments before the return type

template<class T>
   decltype(a*b) add(T a, T b){
   return a + b;
}

But this wont work so you need:

 template<class T>
   auto add(T a, T b) -> decltype(a + b) {
   return a + b;
 }
KostasRim
  • 2,053
  • 1
  • 16
  • 32
7

Is there some difference between using just [...]

No - in your particular example, they are equivalent.


it just visual, or it has some other benefits?

Trailing return types have a few benefits:

  • Easier to switch to automatic return type deduction in the future (just delete everything after ->)

  • Can use parameters as part of the return type

  • Can access class C type aliases without having to say C::

In your particular example, these do not apply.

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416
  • 2
    Read also this [answer](https://stackoverflow.com/questions/11215227/should-the-trailing-return-type-syntax-style-become-the-default-for-new-c11-pr) and this [article](http://www.cprogramming.com/c++11/c++11-auto-decltype-return-value-after-function.html). It can be very useful with lambda and decltype, sizeof – Clonk Jun 11 '18 at 11:03
  • 1
    Not sure if deleting everything after the `->` is really easier than changing the return type from `BOOL` to `auto`. – Baum mit Augen Jun 11 '18 at 11:05