SystemVerilog OOP Mastery · All levels

Parameterized Classes with Type and Value Parameters: Exercises

Exercises for Parameterized Classes with Type and Value Parameters.

Practice exercises

Exercise 1

Create class history #(type T = int, int N = 8) with push(T item) that keeps only the latest N items.

Solution

diagram
Use a queue T q[$]; in push(), q.push_back(item); if (q.size() > N) q.pop_front();. N is compile/elaboration-time fixed per specialization.

Exercise 2

Instantiate one history for byte with N=4 and one for string with N=2, then explain what type checking changes.

Solution

diagram
history#(byte,4) hb = new(); history#(string,2) hs = new();. hb.push() accepts only byte, while hs.push() accepts only string; this is checked at compile/elaboration.

Related topics