C++ Best practices for constants

后端 未结 6 1157
难免孤独
难免孤独 2020-12-09 16:15

I have a whole bunch of constants that I want access to in different parts of my code, but that I want to have easy access to as a whole:

static const bool d         


        
6条回答
  •  一向
    一向 (楼主)
    2020-12-09 16:34

    Another approach which is best for compile times (but has some minor run-time cost) is to make the constants accessible via static methods in a class.

    //constants.h
    class Constants
    {
    public:
      static bool doX();
      static bool doY();
      static int maxNumX();
    };
    
    //constants.cpp
    bool Constants::doX() { return true; }
    bool Constants::doY() { return false; }
    int Constants::maxNumX() { return 42; }
    

    The advantage of this approach is that you only recompile everything if you add/remove/change the declaration of a method in the header, while changing the value returned by any method requires only compiling constants.cpp (and linking, of course).

    As with most things, this may or may not be the best is your particular case, but it is another option to consider.

提交回复
热议问题