How much functionality is “acceptable” for a C++ struct?

后端 未结 19 2366
礼貌的吻别
礼貌的吻别 2021-02-07 09:31

My first post so please go easy on me!

I know that there\'s no real difference between structs and classes in C++, but a lot of people including me use a struct or class

19条回答
  •  我寻月下人不归
    2021-02-07 10:02

    Another common use of structs is for template stuff and local RAII or functor classes. These are one-off bits of code that are closer to functions than they are to whole classes, and requiring the extra public: declaration is just silly. If you look at boost, you'll see a lot of stuff like this:

    template<
          bool C
        , typename T1
        , typename T2
        >
    struct if_c
    {
        typedef T1 type;
    };
    

    It's clearly not a POD (in fact it doesn't hold any data at all). In other cases you can have RAII class that consist of only a constructor/desctructor:

    struct LogOnLeavingScope : public NonCopyable
    {
        string Message;
        LogOnLeavingScope(const string &message) : Message(message) {}
        ~LogOnLeavingScope() { Log(Message); }
    ];
    

    Functor classes would offer the same argument:

    struct Logger
    {
        void operator()(const string &message) { Log(message); }
    }
    

    I'd say there's no one feature of C++ that implies you should use a class instead of a struct (except maybe virtual functions). It's all about what interface you want to present - use a struct if you are ok with everything being public. If you find you are wanting to add private: sections, that a good sign you really want a class instead of a struct.

提交回复
热议问题