Home > other >  auto return types in C function vs specifying return type
auto return types in C function vs specifying return type

Time:01-26

In my work's codebase, I see the following

class custom {
  auto set_data_type(custom_type_t type_t) -> custom & {
    // set some stuff
    // return *this;
  }
}

Why can't we simply just do

class custom {
  custom & set_data_type(custom_type_t type_t) {
    // set some stuff
    // return *this;
  }
}

What is the point of using auto in this case when you already know the return type and already wrote it out in the ->... place?

It seems auto would only be beneficial if it is used with decltype(arg) and where arg may have varying return types?

CodePudding user response:

I would say style.

Moreover, it allows to be consistent in any contexts,

  • simple one (as this one),
  • more useful ones ("complex" decltype(arg) , scoping (-> iterator instead of typename C::iterator)
  • or required one (lambda).

CodePudding user response:

To me the most use of this feature is when you're using nested type when defining a function body in a cpp file:

class MyLongClassName
{
  using ANestedType = ...;

  ANestedType myFunction();
}

When you implement to function body, this syntax avoid some repetition:

MyLongClassName::ANestedType MyLongClassName::myFunction()
{ ... }

versus

auto MyLongClassName::myFunction() -> ANestedType
{ ... }
  •  Tags:  
  • Related