vsoftco
vsoftco

Reputation: 56557

Importing C enum into C++ namespace

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.

Upvotes: 1

Views: 288

Answers (2)

vsoftco
vsoftco

Reputation: 56557

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?

Upvotes: 1

AnT stands with Russia
AnT stands with Russia

Reputation: 320531

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;
}

Upvotes: 4

Related Questions