【问题标题】:Template non-type argument constant restriction Filter library模板非类型参数常量限制过滤器库
【发布时间】:2015-10-26 16:27:14
【问题描述】:

我正在使用 DSP 滤波器库 http://www.linux-usb-daq.co.uk/howto2/filter/

使用模板非类型参数来初始化过滤器对象。这就是过滤器对象的创建和使用方式。

    const int order = 3;
    Iir::Butterworth::LowPass<order> f;
    const float samplingrate = 1000; // Hz
    const float cutoff_frequency = 50; // Hz
    f.setup (order, samplingrate, cutoff_frequency);
    f.reset ();
    FILE *fimpulse = fopen("lp.dat","wt");

// let's generate an input signal and filter it
    // instantly!
    for(int i=0;i<1000;i++) 
    {
            float a=0;
            if (i==10) a = 1; // delta pulse at t=10
            float b = f.filter(a);
            fprintf(fimpulse,"%f\n",b);
    }

现在,如果我想在我的代码中使用这个库来进行 IIR 过滤,以实现不同阶的过滤器,如 3、4、5 等。我应该如何继续,而不必重写整个代码?

因为顺序是编译时常量

const int order = 3;
Iir::Butterworth::LowPass<order> f;

是否有任何技巧可以让我为不同的订单编写此代码而无需重写所有内容?

谢谢,

【问题讨论】:

  • 只需更改订单值

标签: c++ templates filtering signal-processing


【解决方案1】:

如果我理解正确你的问题,你需要两件事:像这样的模板函数

template <int order>
void my_filtering_function(...)
{
    Iir::Butterworth::LowPass<order> f;
    const float samplingrate = 1000; // Hz
...
}

可能还有某种运行时选择,像这样

void exec_filter(int order)
{
    switch (order)
    {
    case 3: my_filtering_function<3>() ;
            break ;
    case 4: my_filtering_function<4>() ;
            break ;
     // othr cases?
    }
}

一些元编程可以自动切换 .eg.一个整数范围。但必须小心操作。您不想将模板函数实例化十亿次...

【讨论】:

    【解决方案2】:

    我在这里看到两个选项:

    • 将通用代码放入模板函数中。它将被参数化为LowPass&lt;order&gt; 类型;

    • 如果公共代码无法进入模板化函数,您可以使用类型擦除技术。但是,您将承担虚函数调用的成本。见http://www.cplusplus.com/articles/oz18T05o/

    【讨论】:

      【解决方案3】:

      看来你想要模板函数:

      template <int order>
      void filter_demo(/*args*/)
      {
          Iir::Butterworth::LowPass<order> f;
          const float samplingrate = 1000; // Hz
          const float cutoff_frequency = 50; // Hz
          f.setup (order, samplingrate, cutoff_frequency);
          f.reset ();
          FILE *fimpulse = fopen("lp.dat","wt");
      
          // let's generate an input signal and filter it
          // instantly!
          for(int i=0;i<1000;i++) 
          {
                  float a=0;
                  if (i==10) a = 1; // delta pulse at t=10
                  float b = f.filter(a);
                  fprintf(fimpulse,"%f\n",b);
          }
      }
      

      然后调用它:

      filter_demo<3>();
      filter_demo<4>();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-03-18
        • 1970-01-01
        • 1970-01-01
        • 2011-08-06
        相关资源
        最近更新 更多