SystemVerilog OOP Mastery · All levels

Specializations, typedef Aliases, and the Per-Specialization Static Gotcha: Code Examples

Code Examples for Specializations, typedef Aliases, and the Per-Specialization Static Gotcha.

Code examples

Independent statics per specialization

systemverilog
class packet #(type T = bit [31:0], int N = 4);
  static int created = 0;
  T payload[N];
  function new();
    created++;
  endfunction
endclass

typedef packet#(bit [7:0], 16) byte_packet_t;
typedef packet#(int, 4)        int_packet_t;

initial begin
  byte_packet_t b1 = new();
  byte_packet_t b2 = new();
  int_packet_t  i1 = new();
  $display("byte=%0d int=%0d", byte_packet_t::created, int_packet_t::created);
end

The display prints different values because each specialization has separate static memory.

Explicitly shared counter across specializations

systemverilog
class packet_stats;
  static int global_created = 0;
endclass

class packet #(type T = int, int N = 4);
  static int created = 0;
  function new();
    created++;
    packet_stats::global_created++;
  endfunction
endclass

Keep created for per-specialization tracking, and packet_stats::global_created for a true global metric.

Related topics