1

I am writing a C++ wrapper for a C library. In the C library, I have a

typedef enum {bar1,bar2} Foo; /* this is defined in the C library */

that I'd like to "bring" into a C++ namespace. I am using

namespace X{
    using ::Foo;
}

to achieve this. However, to qualify the enum members, I always have to refer to them as

X::Foo::bar1 

and so on. Is there any way whatsoever of "importing" the C enum into a C++ namespace but refer directly to the values of the enum as

X::bar1 

and so on? Or, in other words, can I import directly the values of the enum into the namespace?

EDIT

I do not think the question is a dupe, please see my answer as I realized there is a solution.

vsoftco
  • 55,410
  • 12
  • 139
  • 252
  • 1
    Possible duplicate of [using declaration with enum?](https://stackoverflow.com/questions/438192/using-declaration-with-enum) – Alan Birtles Feb 28 '19 at 17:18

2 Answers2

4

That's just how using declaration works. Global Foo and bar1 are two different names. Your using declaration brings name Foo into namespace X, but does not bring any other names from global namespace (like names of the enum members). For that you'd need

namespace X {
  using ::Foo;
  using ::Foo::bar1;
  using ::Foo::bar2;
}
AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
  • I realized I can also do `namespace X{ extern "C" {include } }` which will do it for me. For some reason I though I cannot have C linkage inside namespaces... – vsoftco Feb 28 '19 at 18:10
1

A solution that works for me is to do

namespace X{
    extern "C"{
        #include <C_library.h>
    }
}

Before trying it I had the impression that I cannot put C-linkage functions inside a namespace, but it turns out I was wrong. Then I can simply do

X::bar1

to access the C enum member bar1 from typedef enum {bar1, bar2} Foo;.

See e.g. extern "C" linkage inside C++ namespace?

vsoftco
  • 55,410
  • 12
  • 139
  • 252