3

Does C++ provide a way to declare an object that has the type of a class within a class (e.g. foo_class::bar_class_in_class in the example below) without having to use the scope resolution operator, as it does for a class within a namespace (e.g. foo_namespace::bar_class_in_namespace in example below)?

  namespace foo_namespace {
      class bar_class_in_namespace {
      };

  }

  class foo_class {
  public:
      class bar_class_in_class {
      };
  };


  int main() {
      using namespace foo_namespace;
      bar_class_in_namespace bar_0;

      // Can I access bar_class_in_class without having to use the
      // the scope resolution operator?
      foo_class::bar_class_in_class bar_1;
  }

This question is the same as Can we alias a class name the way we do in namespaces?, with the minor difference that this question asks explicitly about a class within a class.

Jarod42
  • 203,559
  • 14
  • 181
  • 302
plafratt
  • 738
  • 1
  • 8
  • 14
  • 4
    Related: [Can we alias a class name the way we do in namespaces?](https://stackoverflow.com/questions/9791239/can-we-alias-a-class-name-the-way-we-do-in-namespaces) – TrebledJ Mar 14 '19 at 16:54

1 Answers1

8

Yes, C++ offers a way to access the type. What you need is a type alias. Using

using bar_class_in_class = foo_class::bar_class_in_class;

allows you to use bar_class_in_class in place of foo_class::bar_class_in_class. This is scoped so if you do it in main, you can only see the alias in main


Do note that you can also "change the name" of the inner type

using my_type = foo_class::bar_class_in_class;

does the same thing as above, but you would use my_type as the type name. This can be a nice convenience.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402