Units of measurement in C++

China☆狼群 提交于 2019-12-02 20:43:36

I know you mentioned you aren't using C++11 but others looking at this question may be, so here's the C++11 solution using user defined literals:

http://ideone.com/UzeafE

#include <iostream>
using namespace std;

class Frequency
{
public:
    void Print() const { cout << hertz << "Hz\n"; }

    explicit constexpr Frequency(unsigned int h) : hertz(h) {}
private:
    unsigned int hertz;
};
constexpr Frequency operator"" _Hz(unsigned long long hz)
{
    return Frequency{hz};
}
constexpr Frequency operator"" _kHz(long double khz)
{
    return Frequency{khz * 1000};
}

int main()
{
    Frequency(44100_Hz).Print();
    Frequency(44.1_kHz).Print();
    return 0;
}

Output:

44100Hz
44100Hz

The Boost "Units" library is great for this type of thing.

http://www.boost.org/doc/libs/1_55_0/doc/html/boost_units.html

You can use the factory design pattern to accomplish what you're looking for. You can create a frequency class with a private constructor and several static methods that will construct the object depending on the units the user wants to use. By keeping the constructor private, the user is forced to declare his units explicitly, which reduces the likelihood of user error.

#include <iostream>

using namespace std;

class frequency
{
public:
  static frequency hertz(int hz)
  {
    return frequency(hz);
  }

  static frequency kilohertz(double kHz)
  {
    return frequency(kHz * KHZ_TO_HZ);
  }

  static frequency rpm(int rpm)
  {
    return frequency(rpm * RPM_TO_HZ);
  }

  int hz()
  {
    return m_hz;
  }

private:
  static const int KHZ_TO_HZ = 1000;
  static const int RPM_TO_HZ = 60;

  frequency(int hz) : m_hz(hz)
  {
  }

  int m_hz;
};

int main()
{
  wcout << frequency::hertz(44100).hz() << "Hz" << endl;
  wcout << frequency::kilohertz(44.100).hz() << "Hz" << endl;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!