'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?



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1