You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SystemVerilog中如何向函数传递with子句?

SystemVerilog my_queue类find_index实现方案

SystemVerilog不支持直接传递with子句作为函数参数,因为with是语法关键字,不属于可传递的类型或对象。以下是两种可行的替代实现方案:

方案一:函数指针回调(简单匹配场景)

通过定义匹配函数的指针类型,让调用者传入具体的匹配逻辑,在find_index内部遍历队列完成匹配:

class my_queue #(type T);
    typedef T queue_t[$];
    typedef int int_q[$];
    // 定义匹配函数指针:输入T类型元素,返回bit表示是否匹配
    typedef function bit match_func(T item);
    protected queue_t m_queue;

    function void push_back(T item);
        m_queue.push_back(item);
        // 覆盖率统计等额外操作
    endfunction

    function T pop_front();
        // 覆盖率统计等额外操作
        return m_queue.pop_front();
    endfunction

    function int_q find_index(match_func match);
        int_q indices;
        foreach(m_queue[i]) begin
            if(match(m_queue[i])) begin
                indices.push_back(i);
            end
        end
        return indices;
    endfunction
endclass

使用示例

my_queue#(int) q = new();
q.push_back(10);
q.push_back(20);
q.push_back(10);

// 查找值等于10的元素索引
int idx_list[$] = q.find_index( function bit(int item) return item == 10; );
// idx_list结果为 '{0, 2}

方案二:参数化匹配类(复杂/可复用场景)

如果需要更复杂的匹配逻辑(比如带状态的匹配、可复用的匹配规则),可以定义抽象基类,让调用者实现具体匹配子类:

// 抽象匹配基类
virtual class matcher #(type T);
    pure virtual function bit match(T item);
endclass

class my_queue #(type T);
    typedef T queue_t[$];
    typedef int int_q[$];
    protected queue_t m_queue;

    function void push_back(T item);
        m_queue.push_back(item);
        // 覆盖率统计等额外操作
    endfunction

    function T pop_front();
        // 覆盖率统计等额外操作
        return m_queue.pop_front();
    endfunction

    function int_q find_index(matcher#(T) match_obj);
        int_q indices;
        foreach(m_queue[i]) begin
            if(match_obj.match(m_queue[i])) begin
                indices.push_back(i);
            end
        end
        return indices;
    endfunction
endclass

使用示例

// 实现具体匹配类:查找大于15的元素
class gt_15_matcher extends matcher#(int);
    function bit match(int item);
        return item > 15;
    endfunction
endclass

my_queue#(int) q = new();
q.push_back(10);
q.push_back(20);
q.push_back(25);

gt_15_matcher matcher = new();
int idx_list[$] = q.find_index(matcher);
// idx_list结果为 '{1, 2}

方案选择建议

  • 简单匹配逻辑优先用方案一,代码更简洁,调用成本低;
  • 需要复用匹配规则或实现复杂状态匹配时,用方案二,扩展性更强。

内容的提问来源于stack exchange,提问作者Melandru's Square

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 01:36:34