Why are C++ classes allowed to have zero data members?

前端 未结 6 2148
遥遥无期
遥遥无期 2020-12-20 16:46

question about c++ why minimal number of data members in class definition is zero

i think it should be one , i.e pointer to virtual table defined by compiler

6条回答
  •  情话喂你
    2020-12-20 17:43

    I’m working on a library that sometimes even uses types that – gasp! – aren’t even defined, much less have data members!

    That is, the type is incomplete, such as

    struct foobar;
    

    This is used to create an unambiguous name, nothing more.

    So what is this useful for? Well, we use it to create distinct tags, using an additional (empty, but fully defined) type:

    template 
    struct Tag { };
    

    Now you can create distinct tags like so:

    struct TagForward_;
    typedef Tag ForwardTag;
    
    struct TagRandomAccessible_;
    typedef Tag RandomAccessibleTag;
    

    These in turn can be used to disambiguate specialized overloads. Many STL implementations do something similar:

    template 
    void sort(Iter begin, Iter end, RandomAccessibleTag const&) …
    

    Strictly speaking, the indirect route via a common Tag class template is redundant, but it was a useful trick for the sake of documentation.

    All this just to show that a (strict, static) type system can be used in many different ways than just to bundle and encapsulate data.

提交回复
热议问题