Ready-to-run snippets

Code Examples

Ready-to-run Verilog, SystemVerilog, and UVM examples. Click any to open it live in the IDE.

← All examples

Pass Datatype As A Parameter

SystemVerilog Classes & OOP

A class parameterized by #(type T = int) used as an int, a 4-bit vector and a real, so the same method behaves differently per type.

Open in IDE
testbench.sv
// "T" is a parameter that is set to have a default value of "int"
// Hence "items" will be "int" by default 
class stack #(type T = int);
  T item;             
	
  function T add_a (T a); 	
    return item + a;
  endfunction
endclass

module tb;
	stack 			 	st; 	// default - a stack of ints
	stack #(bit[3:0]) 	bs; 	// a stack of 4-bit vector
	stack #(real) 		rs; 	// a stack of real numbers
  
  	initial begin
      st = new;
      bs = new;
      rs = new;
      
      // Assign different values, and add 10 to these values
      // Then print the result - Note the different values printed
      // that are affected by change in data type
      st.item = -456;
      $display ("st.item = %0d", st.add_a (10));
      
      bs.item = 8'hA1;
      $display ("bs.item = %0d", bs.add_a (10));
      
      rs.item = 3.14;
      $display ("rs.item = %0.2f", rs.add_a (10));
    end
endmodule

/* 
Simulation Log:
---------------
ncsim> run
st.item = -446
bs.item = 11
rs.item = 13.14
ncsim: *W,RNQUIE: Simulation is complete.
ncsim> exit
*/
design.sv
// Code your design here
Admin mode — edit and delete controls are visible on each row. Use the IDE to add new snippets via File → Save as Snippet.