123. Register Operator Overloading

#include <cstdint>
#include <cstdio>

// Register abstraction
class Register32 {
public:
    explicit Register32(std::uint32_t v = 0) : value(v) {}

    Register32& operator|=(std::uint32_t mask) {
        value |= mask;
        return *this;
    }

    Register32& operator&=(std::uint32_t mask) {
        value &= mask;
        return *this;
    }

    std::uint32_t get() const {
        return value;
    }

private:
    std::uint32_t value;
};

int main() {
    Register32 reg{0};

    int n;
    std::scanf("%d", &n);

    for (int i = 0; i < n; ++i) {
        char op[6];
        int bit;
        std::scanf("%s %d", op, &bit);

        if (op[0] == 'S') {
            reg |= (1u << bit);
        } else {
            reg &= ~(1u << bit);
        }
    }

    std::printf("reg=%u\n", reg.get());
    return 0;
}

Explanation & Logic Summary:

The firmware logic interacts with the register exclusively through overloaded operators.
The Register32 class encapsulates the register state using a private data member and exposes controlled mutation via |= and &= operators.

All operator overloads are non-virtual member functions, ensuring:

  • Compile-time resolution
  • No runtime overhead
  • No dynamic dispatch

The fixed main() function guarantees that correctness depends solely on proper operator overloading and class design.

Firmware Relevance & Real-World Context:

This problem reflects real embedded firmware practices where:

  • Hardware registers are wrapped in lightweight C++ abstractions
  • Operator overloading improves clarity without affecting performance
  • Encapsulation prevents accidental misuse
  • Compile-time behavior is essential for deterministic firmware

The exercise directly strengthens Embedded C++ operator overloading, register abstraction, and HAL-style design skills.

 

 

 

Loading...

Input

3 SET 0 SET 3 CLEAR 0

Expected Output

reg=8