std::chrono 频率?

std::chrono for frequencies?

我正在实现一个非常简单的带通滤波器,它的输入参数是一个向量,其中包含信号、驻留时间以及高通和低通滤波器的截止频率:

typedef std::vector<double> vec;
vec bandPass(const vec& signal, double dwellTime, double lowCutoff, double highCutoff);

我的界面的明显问题是函数调用者必须提前知道期望的时间和频率单位,并且可能不得不在必要时适当地转换它们。

我想我也许可以使用 std::chrono 来解决我的问题,但我还没有看到它被用来测量频率。我想要:

vec bandPass(const vec& signal, milliseconds dwellTime, kHertz lowCutoff, kHertz highCutoff);

并让我的函数将所有单位转换为秒和赫兹以进行计算。理想情况下,将毫秒和 kHz 相乘会得到与将秒和 Hz 相乘相同的结果。

有没有人遇到过类似的问题?写类似 1/10s 的东西来引用 Hertz 是合法的 C++ 吗?

我对 std::chrono(以及 C++,就此而言)没有太多经验,希望在定义我的界面之前能在这里收集一些智慧的话。也欢迎任何其他建议。

一个频率可以看作是一个周期的持续时间。所以20赫兹可以被视为0.05秒。

Chrono 将完全支持。

您或许可以编写一个 Hz 类型或频率模板,它在某些情况下与 periods/durations 的做法相反。遗憾的是,内部存储持续时间效果不佳,因为以秒为单位的 int Hz 作为以秒为单位的持续时间是失败的。

template<
  class Rep,
  class Period = std::ratio<1>
>
struct frequency;

template<
  class Rep,
  std::intmax_t Num,
  std::intmax_t Denom>
>
struct frequency<Rep, std::ratio<Num, Denom>>
{
  // todo!
  frequency& operator+=(const frequency& d);
  frequency& operator-=(const frequency& d);
  frequency& operator*=(const Rep& rhs);
  frequency& operator/=(const Rep& rhs);
  frequency& operator%=(const frequency& rhs);
  Rep count() const;
  friend frequency operator+(frequency lhs, frequency const& rhs);
  friend frequency operator-(frequency lhs, frequency const& rhs);
  friend frequency operator*(frequency self, Rep const& scalar);
  friend frequency operator*(Rep const& scalar, frequency self);
  friend frequency operator/(frequency self, Rep const& scalar);
  friend frequency operator%(frequency lhs, Rep const& rhs);
  friend frequency operator%(frequency lhs, frequency const& rhs);
  friend bool operator==(frequency const& lhs, frequency const& rhs);
  friend bool operator!=(frequency const& lhs, frequency const& rhs);
  friend bool operator<=(frequency const& lhs, frequency const& rhs);
  friend bool operator>=(frequency const& lhs, frequency const& rhs);
  friend bool operator<(frequency const& lhs, frequency const& rhs);
  friend bool operator>(frequency const& lhs, frequency const& rhs);
  template<class ToFrequency>
  friend ToFrequency duration_cast(frequency const& self);
  // etc
};

template<class Rep>
using hertz = frequency<Rep>;

template<class T>
hertz<T> operator "" _hz(T t) {
  return hertz<T>(std::move(t));
}

现在 13_hzfrequency<int, std::ratio<1,1>> 类型的对象。