Include an empty base class pointer to a pointer to a child class?

I have some code that uses somewhat hidden drops from the type of the base class to the type of the child class, where the type of the child class is specified as a template parameter. I assume that since the base class does not declare any data elements and is of zero size, the address of the base class pointer will be the same as that of the child, and the cast will succeed. So far, the code is working correctly.

Here is a simplified version of what I'm doing:

template <class RangeT>
struct CppIterator {
    CppIterator(const RangeT& range) { ... }
    // ... methods calling RangeT members
};

// Base class, provides begin() / end() methods. 
template<class RangeT>
struct CppIterableBase {
    CppIterator<RangeT> begin() { 
        return CppIterator<RangeT>( *(RangeT*)this );  // Is this safe?
    }
    CppIterator<RangeT> end() { ... }
};

struct MyRange : CppIterableBase<MyRange> {
    // ... 
};

My main question is is the code is kosher? Will the base pointer always equate to the child pointer if the base is empty? Does it depend on the implementation? Will I get in trouble?

He solves my problem beautifully, but I doubt a little.

+4
2

, .

, , -- , static_cast - --. , .

, , , ( CRTP).

,

reinterpret_cast , , , undefined ( , , UB). C reinterpret_cast (, Foo Base<Baz>, Baz Base<Baz>), .

, , Foo Base<Bar>, static_cast , Bar Base<Bar>.

+2

CRTP.

static_cast<Derived*>(this) , C- " ".

Foo<> CRTP:

Foo<Derived> Derived, static_cast<Derived*>(this) .

A static_assert of is_base_of , . struct Bar : Foo<Derived> undefined, , .

+2

All Articles