Example of useful downcast with static_cast which does not produce undefined behaviour

I am wondering about a short code example of an application of downcast via static_cast, under conditions where there is no undefined behaviour. I have looked around and I found quite a few texts (posts, Q&A, etc.) referring to fragments of the standard, explaining, etc. But I found no examples that illustrate that (and that surprises me).

Could anyone provide one such example?

Upvotes: 0

Views: 134

Answers (2)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 123440

A downcast via static_cast is part of the typical implementation of the Curiously recurring template pattern (CRTP). The example from wikipedia:

template <class T> 
struct Base
{
    void interface()
    {
        // ...
        static_cast<T*>(this)->implementation();
        // ...
    }

    static void static_func()
    {
        // ...
        T::static_sub_func();
        // ...
    }
};

struct Derived : Base<Derived>
{
    void implementation();
    static void static_sub_func();
};

Base "knows" that it can downcast this to T* via static_cast (rather than dynamic_cast) because the whole purpose of Base is to be inherited by T. For more details on CRTP I refer you to the wikipedia article.

Upvotes: 5

idmean
idmean

Reputation: 14915

A very basic example:

class Animal {};
class Dog : public Animal {};

void doSomething() {
  Animal *a = new Dog();
  Dog *d = static_cast<Dog*>(a);
}

A more contrived example:

class A { public: int a; };
class B : public A {};
class C : public A {};
class D : public B, public C {};

void doSomething() {
  D *d = new D();
  int bValue = static_cast<B*>(d)->a;
  int cValue = static_cast<C*>(d)->a;

  // This does not work because we have two a members in D!
  // int eitherValue = d->a;
}

There are also countless other cases where you know the actual type type of the instance due to some flags or invariants in your program. However, many sources recommend preferring dynamic_cast in all cases to avoid errors.

Upvotes: 2

Related Questions