Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a 'using' statement for enum classes? [duplicate]

In a rock, paper, scissors program that I am writing, I am enumerating the three different moves and declaring them as a class. However, when I try to write a using statement so that I have to avoid using the scope operator, it doesn't seem to work. Anyone know why?

enum class choice {rock, paper, scissors};

using namespace choice;

Here an error message comes up, saying: [Error] 'choice' is not a namespace name. Why is this? I thought that for choice could be a namespace, in this context.

like image 301
Victor Odouard Avatar asked Jun 07 '13 00:06

Victor Odouard


3 Answers

It will be possible in C++20, P1099R5 :

enum class choice {rock, paper, scissors};

using enum choice;
like image 156
Baptistou Avatar answered Sep 22 '22 10:09

Baptistou


namespace choice
{
    enum class type {rock, paper, scissors};
    constexpr auto rock     = type::rock    ;
    constexpr auto paper    = type::paper   ;
    constexpr auto scissors = type::scissors;
}

int main()
{
    choice::type move;
    using namespace choice;
    move = rock;
    move = paper;
    move = scissors;

    return 0;
}
like image 29
anton_rh Avatar answered Sep 20 '22 10:09

anton_rh


The behaviour you want can be achieved with namespace choice { enum choice { ... }; }. It will work only for values though, you still have to use choice::choice if you want to declare a variable. Unless you also use auto, of course.

like image 35
catscradle Avatar answered Sep 22 '22 10:09

catscradle