How to make "use" of weak enumerations in C ++ 11?

I have an enum definition inside a class in the header:

namespace A {

class B {
 public:
  enum Value {
    VALUE1 = 1,
    VALUE2 = 2,
  };
};

}

And I want to use its values ​​in the source file without a prefix, for example:

#include "header"

int main() {
  someFn(VALUE1);

  return 0;
}

I tried using A::B::Value;, but clang gives an error:

Using declaration cannot refer to class member


Even if I move enum outside the class:

namespace A {

enum Value {
  VALUE1 = 1,
  VALUE2 = 2,
};    

}

and do using A::Value;, the error went away, but the compiler complains about VALUE1:

use of undeclared identifier "VALUE1"

Is there a way to use enum values ​​without any prefixes if the enum is defined elsewhere? - Use is #defineout of the question.

If there is no way, then what is the possible problem with implementing this behavior in C ++ Standard?

+4
4

:

  • BЈћ: , . [namespace.udecl]/8.

  • using A::B::Value;, enum, . , :

    namespace Values { enum Value{ VALUE1, VALUE2 }; }
    using Values::Value;  // don't pollute my scope with the enumerators
    
    Value v = Values::VALUE1;
    

:

namespace A
{
    namespace B
    {
        enum Value
        {
              VALUE1
            , VALUE2
        };
    }
}

int main()
{
    using A::B::Value;
    using A::B::VALUE1;
    using A::B::VALUE2;

    Value v = VALUE1;
    v = VALUE2;
}

, hvd , using :

namespace A
{
    namespace B
    {
        enum Value
        {
              VALUE1
            , VALUE2
        };
    }
}

int main()
{
    using namespace A::B;

    Value v = VALUE1;
    v = VALUE2;
}
+2

: , .

class B namespace B:

namespace A {

namespace B {
  enum Value {
    VALUE1 = 1,
    VALUE2 = 2,
  };
};

}

( ):

using A::B::Value
+3

Enumerations are processed similarly to classes. Think about this while trying to do the following:

class Value
{
public:
    static const int VALUE1 = 0;
};

using Value::VALUE1; // ERROR class-qualified name

In short: you cannot make enum values ​​visible this way with the operator using.

0
source

Well, the closest I can think of:

namespace A {
  class B {
  public:
    enum Value { VALUE1 = 1, VALUE2 = 2 };
  };
};

const A::B::Value VALUE1 = A::B::VALUE1;

int main () {
  return VALUE1;
}

but its quite tiring and error prone and absolutely not worth it. :)

0
source

All Articles