Type ambiguity

Type ambiguity

This program has compilation errors that arise from ambiguous enum values. Resolve them without renaming the enumerations, and make sure that the developer isn't able to misuse a direction or rotation by mixing the LEFT and RIGHT values inside Direction and Rotation. Run the program to ensure it works as intended.

#include <iostream>

enum Direction {
    LEFT,
    RIGHT,
    UP,
    DOWN
};

enum Rotation {
    LEFT,
    RIGHT
};

void moveRobot(Direction direction) {
    switch (direction) {
        case LEFT: std::cout << "Moving left." << std::endl; break;
        case RIGHT: std::cout << "Moving right." << std::endl; break;
        case UP: std::cout << "Moving up." << std::endl; break;
        case DOWN: std::cout << "Moving down." << std::endl; break;
    }
}

void rotateRobot(Rotation rotation) {
    switch (rotation) {
        case LEFT: std::cout << "Rotating left." << std::endl; break;
        case RIGHT: std::cout << "Rotating right." << std::endl; break;
    }
}

int main() {
    moveRobot(LEFT);
    rotateRobot(LEFT);
    return 0;
}

Expected output:

Moving left.
Rotating left.

Hint

Use enum class or enum struct to scope an enum

Answer

Using enum class for Direction and Rotation ensures that the enum values are scoped within their respective enums, preventing name conflicts.

All uses of the enum values are prefixed with the enum class name (e.g., Direction::LEFT) to ensure clarity and type safety.

#include <iostream>

enum class Direction {
    LEFT,
    RIGHT,
    UP,
    DOWN
};

enum class Rotation {
    LEFT,
    RIGHT
};

void moveRobot(Direction direction) {
    switch (direction) {
        case Direction::LEFT: std::cout << "Moving left." << std::endl; break;
        case Direction::RIGHT: std::cout << "Moving right." << std::endl; break;
        case Direction::UP: std::cout << "Moving up." << std::endl; break;
        case Direction::DOWN: std::cout << "Moving down." << std::endl; break;
    }
}

void rotateRobot(Rotation rotation) {
    switch (rotation) {
        case Rotation::LEFT: std::cout << "Rotating left." << std::endl; break;
        case Rotation::RIGHT: std::cout << "Rotating right." << std::endl; break;
    }
}

int main() {
    moveRobot(Direction::LEFT);
    rotateRobot(Rotation::LEFT);
    return 0;
}
Questions