Trailing return type

360 Views Asked by At

I see a lot of this kind of code statements in one of well known C++ unit test framework.

This is inline class member function.

auto exeName() const -> std::string {
  return m_exeName;
}

What benefits does it give? Wouldn't it be the same to write

std::string exeName() const {
  return m_exeName;
}

I understand what are benefits of trailing return type. But if function returns just string or int or other basic type why we can't just use well known syntax?

1

There are 1 best solutions below

2
On
  • It is the only way to do it (explicitly) for lambda:

    auto l = []() -> int {/*..*/};
    
  • Benefits comes when using decltype:

    template <typename T>
    auto sum(T a, T b) -> decltype(a + b);
    

    versus

    template <typename T>
    decltype(std::declval<T>() + std::declval<T>()) sum(T a, T b);
    
  • Similarly, with inner types:

    auto Container::begin() -> iterator;
    

    versus

    Container::iterator Container::begin();
    
  • Another benefit is with "complex" return type syntax

    auto get_func() -> int (*)(char);
    

    versus

    int (*get_func())(char);
    

    or

    auto ::C::foo() -> D;
    

    versus

    D (::C::foo()); // D ::C::foo() would be parsed as D::C::foo();
    

Then consistency with above code.