What's the best way to force the user of a C++ function to acknowledge the semantic meaning of parameters that are numerical constants?

后端 未结 7 2097
故里飘歌
故里飘歌 2021-02-13 15:27

I\'d like to write function interfaces that force the user to acknowledge the semantic meaning of built-in constants. For example, I\'d like to take

void rotate(         


        
7条回答
  •  后悔当初
    2021-02-13 15:36

    The key to this constraint is to declare your constructor explicit:

    class Radians
    {
    public:
      explicit Radians(float value) : m_value(value) {}
    private:
      float m_value;
    };
    

    That way your user can't type rotate(4.5). They'll have to type rotate(Radians(4.5)).

提交回复
热议问题