Units of measurement in C++

后端 未结 3 1752
后悔当初
后悔当初 2021-02-02 14:42

I\'m working on a game engine, and currently I\'m stuck designing the IO system. I\'ve made it so, the engine itself doesn\'t handle any file formats, but rathe

3条回答
  •  轮回少年
    2021-02-02 15:35

    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 
    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
    

提交回复
热议问题