Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referring to a class defined inside a function scope

Tags:

c++

scoping

c++14

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?

like image 316
Heatsink Avatar asked Mar 13 '14 16:03

Heatsink


1 Answers

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`
  }
}
like image 62
Jonathan Wakely Avatar answered Oct 05 '22 00:10

Jonathan Wakely