find size of derived class object using base class pointer

前端 未结 4 1231
名媛妹妹
名媛妹妹 2020-12-09 09:32

Is it possible to find the size of a derived class object using a base class pointer, when you don\'t know the derived type.

Thank you.

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-09 10:17

    There's no direct way, but you can write a virtual size() method child classes can implement. An intermediary templates class can automate the leg work.

    struct base {
      virtual size_t size() const =0;
      virtual ~base() { }
    };
    
    template 
    struct intermediate : base {
      virtual size_t size() const { return sizeof(T); }
    };
    
    struct derived : intermediate 
    { };
    

    This does require your hierarchy be polymorphic... however, requesting behavior based on the dynamic type of an object rather than its static type is part of the definition of polymorphic behavior. So this won't add a v-table to the average use case, since at the very least you probably already have a virtual destructor.

    This particular implementation does limit your inheritance tree to a single level without getting into multiple inheritance [ie, a type derived from derived will not get its own override of size]. There is a slightly more complex variant that gets around that.

    struct base { /*as before */ };
    
    template
    struct intermediate : Base {
      virtual size_t size() const { return sizeof(Derived); }
    };
    
    struct derived : intermediate
    { };
    
    struct further_derived : intermediate
    { };
    

    Basically, this inserts an intermediate in between each actual layer of your hierarchy, each overriding size with the appropriate behavior, and deriving from the actual base type. Repeat ad nauseum.

    //what you want
    base >> derived 
         >> more_deriveder
         >> most_derivedest
    
    //what you get
    base >> intermediate 
         >> derived >> intermediate 
         >> more_deriveder >> intermediate 
         >> most_derivedest
    

    Several mixin-type libraries make use of such a scheme, such that the mixins can be added to an existing hierarchy without introducing multiple inheritance. Personally, I rarely use more than a single level of inheritance, so I don't bother with the added complexity, but your mileage may vary.

提交回复
热议问题