Compile-Time Power-of-Two Validator

#include <iostream>

// TODO: Define Class Template 'PowerOfTwoBuffer'
// Parameter: int Size
template <int Size>
class PowerOfTwoBuffer {
public:
    // TODO: Add static_assert to ensure Size is Power of Two
    // Logic: (Size & (Size - 1)) == 0
    static_assert((Size&(Size - 1))==0);

    // TODO: Implement getWrappedIndex(int raw_index)
    // Logic: raw_index & (Size - 1)
    int getWrappedIndex(int raw_index) {
        return raw_index & (Size-1); // Placeholder
    }
};

int main() {
    // Instantiate with a valid power of two (16)
    PowerOfTwoBuffer<16> buffer;
    
    // Uncommenting the line below should cause a COMPILER ERROR
    // PowerOfTwoBuffer<10> invalid_buffer; 

    int N;
    if (!(std::cin >> N)) return 0;

    for (int i = 0; i < N; ++i) {
        int raw;
        std::cin >> raw;
        std::cout << "Wrapped: " << buffer.getWrappedIndex(raw) << std::endl;
    }
    return 0;
}

Solving Approach

 

 

 

 

Upvote
Downvote
Loading...

Input

3 5 16 20

Expected Output

Wrapped: 5 Wrapped: 0 Wrapped: 4