C++ Best practices for constants

后端 未结 6 1153
难免孤独
难免孤独 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:36

    I think your base assumption is off.

    Your other headers are usually organized by keeping together what works together. For example, a class and its related methods or two classes heavily interlinked.

    Why group all constants in a single header ? It does not make sense. It's about as bad an idea as a "global.h" header to include every single dependency easily.

    In general, the constants are used in a particular context. For example, an enum used as a flag for a particular function:

    class File {
    public:
      enum class Mode {
        Read,
        Write,
        Append
      };
    
      File(std::string const& filename, Mode mode);
    
      // ...
    };
    

    In this case, it is only natural that those constants live in the same header that the class they are bound to (and even within the class).

    The other category of constants are those that just permeate the whole application. For example:

    enum class Direction {
      Up,
      Down,
      Right,
      Left,
      Forward,
      Backward
    };
    

    ... in a game where you want to express objects' move regarding the direction they are facing.

    In this case, creating one header file for this specific set of constants is fine.

    And if you really are worried about grouping those files together:

    constants/
      Direction.hpp
      Sandwich.hpp
      State.hpp
    

    And you will neatly sidestep the issue of recompiling the whole application when you add a constant... though if you need to, do it, you're paying the cost only once, better than a wrong-sided design you'll have to live off with for the rest of your work.

提交回复
热议问题