namespace & static_cast

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
enum class StudentNames
{
    KENNY, // 0
    KYLE, // 1
    STAN, // 2
    BUTTERS, // 3
    CARTMAN, // 4
    WENDY, // 5
    MAX_STUDENTS // 6
};
 
int main()
{
    int testScores[StudentNames::MAX_STUDENTS]; // allocate 6 integers
    testScores[StudentNames::STAN] = 76;
}

compiler error fixed with static_cast

1
2
3
4
5
int main()
{
    int testScores[static_cast<int>(StudentNames::MAX_STUDENTS)]; // allocate 6 integers
    testScores[static_cast<int>(StudentNames::STAN)] = 76;
}


below regular enum with namespace negates use of static_cast with enum Class x (easier). How does namespacing this work though? I know the regular enum implicitly converts to integer, but what does the namespacing do?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
namespace StudentNames
{
    enum StudentNames
    {
        KENNY, // 0
        KYLE, // 1
        STAN, // 2
        BUTTERS, // 3
        CARTMAN, // 4
        WENDY, // 5
        MAX_STUDENTS // 6
    };
}
 
int main()
{
    int testScores[StudentNames::MAX_STUDENTS]; // allocate 6 integers
    testScores[StudentNames::STAN] = 76;
}
Last edited on
below regular enum with namespace negates use of static_cast. How does namespacing this work? I know the regular enum implicitly converts to integer.


That's right enum does implicitly convert to int, enum class doesn't and requires the static_cast

It's nothing to do with the namespace, although it is a very good idea to put your own code in it's own namespace/s.

I wouldn't name variable the same as a namepsace though.

This link shows an example of using a scoped enum (enum class) with a switch

http://en.cppreference.com/w/cpp/language/enum
Thx
Thanks
Topic archived. No new replies allowed.