C++ Logo

sg12

Advanced search

Re: [ub] type punning through congruent base class?

From: Fabio Fracassi <f.fracassi_at_[hidden]>
Date: Mon, 6 Jan 2014 18:10:38 +0100
> On 6 January 2014 17:34, Fabio Fracassi <f.fracassi_at_[hidden]> wrote:
> > It would enable us to extend or change the interface of a class
> > without copying or moving the underlying object (think mixin without
> additional data).
>
> Why don't you just construct D with a B&?

Because I do not want a new object ... I want to use the existing one
(over which I have no (or do not want to take) control) with the extended
interface. Something along these lines:

struct fooable_vec : std::vector<int> {
   void foo1();
   void foo2() const;
};

auto make_fooable(std::vector& v) { return static_cast<fooable_vec&>(v); }

void do_stuff(fooable_vec& fv) {
   fv.foo1();
   fv.foo2();
}

auto v = std::vector<int>(1'000'000);
std::iota(v.begin(), v.end(),1);
...
do_stuff(make_fooable(v));
...

I do not want v to be copied or moved, and I do not want fooable_vec to
contain an indirection either.

best regards

Fabio

Received on 2014-01-06 18:11:02