what's `auto classMemberFunction()->void {}` signature?

1k views Asked by At

I've seen in an article a code similar to this one:

#include <iostream>

class MyClass {
public:

  auto myFunction(int i)->void {
    std::cout << "Argument is " << i << std::endl;
  }
};

void main() {
  MyClass myClass;
  myClass.myFunction(4);
}

The program prints correctly the output Argument is 4, but I don't understand the signature of the class function member and what's its difference with the usual one. When it's useful to use this different signature rather than void myFunction(int i)?

1

There are 1 answers

2
Quentin On BEST ANSWER

This is an (ab)use of the trailing-return-type syntax that has been introduced in C++11. The syntax is:

auto functionName(params) -> returnType;
auto functionName(params) -> returnType { }

It works the same as a classic function declaration with the return type on the left, except that the trailing type can use names introduced by the function's signature, i.e:

T    Class::function(param);      // No particular behaviour
auto Class::function(param) -> T; // T can use Class::Foo as Foo, decltype(param), etc.

In this case though, there is no point except consistency.