Frage

In C++1y, it is possible for a function's return type to involve locally defined types:

auto foo(void) {
  class C {};
  return C();
}

The class name C is not in scope outside the body of foo, so you can create class instances but not specify their type:

auto x            = foo(); // Type not given explicitly
decltype(foo()) y = foo(); // Provides no more information than 'auto'

Sometimes it is desirable to specify a type explicitly. That is, it is useful to write "the type C that is defined in foo" instead of "whatever type foo returns." Is there a way to write the type of foo's return value explicitly?

War es hilfreich?

Lösung

auto x            = foo(); // Type not given explicitly
decltype(foo()) y = foo(); // Provides no more information than 'auto'

So what? Why do you care what the type's "real" name is?

As dyp said in a comment, you can use a typedef to give it a name, if that makes you feel better than auto:

 using foo_C = decltype(foo());

Sometimes it is desirable to specify a type explicitly. That is, it is useful to write "the type C that is defined in foo" instead of "whatever type foo returns." Is there a way to write the type of foo's return value explicitly?

No.

There is no name for "the function scope inside foo()" just like there is no name for these scopes:

void bar()
{
  int i=0;
  // this scope does not have a name, cannot qualify `i`
  {
    int i=1;
    // this scope does not have a name, cannot qualify either `i`
  }
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top