C++ "Importing" an enum class from another C++ file

Viewed 8208

I'm a coming from a Java background so please bear with me on this :)

I'm trying to "import" (to use Java terminology) an enum class from another C++ file so as to be able to use it directly without having to prefix it with the class name.

So for instance, let's say I have this in a header file:

class Foo
{
    public:
        enum class Bar {ITEM_1, ITEM_2};
        void doThings(Bar bar);
};

Now, currently, if I want to use Bar from another C++ file, I do this:

#include "Foo.h"

void Foo2::methodInAnotherFile()
{
    Foo foo();
    Foo::Bar bar = Foo::Bar::ITEM_2;
    foo.doThings(bar);
}

Now what I'd like to do is to be able to do something like "import" (to use Java terminology) Bar so as to be able to remove the need to prefix Bar with Foo::, i.e. do Bar bar = Bar::ITEM_2;.

Now, with my limited knowledge of C++, one way I can think of doing this would be to surround all the code in Foo.h with namespace FooNamespace{}, take the Bar enum out of the class (but still in the namespace), and then add using namespace FooNamespace to the top of the Foo2 class. However, for my application that really doesn't make much logical sense, as the Bar enum really logically belongs inside that Foo class.

Since I'm proficient in Java, here's a Java example of what I'd like to do:

File 1:

package org.fooclass;

public class Foo
{
    public static enum Bar
    {
        ITEM_1,
        ITEM_2;
    }

    public void doThings(Bar bar)
    {
        System.out.println("Item: " + bar.toString());
    }
}

File 2:

package org.foo2class;

import org.fooclass.Foo;
import org.fooclass.Foo.Bar; //I want to do THIS in C++

public class Foo2
{
    public void methodInAnotherFile()
    {
        Foo foo = new Foo();

        /*
         * Since I've 'imported' Foo.Bar, I can now
         * use Bar directly instead of having to do this:
         * Foo.Bar bar = Foo.Bar.ITEM2;
         */
        Bar bar = Bar.ITEM_2;

        foo.doThings(bar);
    }
}
1 Answers

Use a type alias via a using statement, eg:

#include "Foo.h"

using Bar = Foo::Bar; // <-- here

void Foo2::methodInAnotherFile()
{
    Foo foo;
    Bar bar = Bar::ITEM_2;
    foo.doThings(bar);
}

Or, to limit its scope:

#include "Foo.h"

void Foo2::methodInAnotherFile()
{
    using Bar = Foo::Bar; // <-- here
    Foo foo;
    Bar bar = Bar::ITEM_2;
    foo.doThings(bar);
}
Related