An "upcast", i.e. a conversion from a pointer to an object to a pointer to a base subobject, always succeeds if the base is unambiguous and accessible, and so it's fine to use implicit_cast.

Synopsis

Declared in <absl/base/casts.h>

template<
    typename To,
    typename From>
[[nodiscard]]
To
down_cast(From* f);

Description

A "downcast", i.e. a conversion from a pointer to an object to a pointer to a more‐derived object that may contain the original object as a base subobject, cannot safely be done using static_cast, because you do not generally know whether the source object is really the base subobject of a containing, more‐derived object of the target type. Thus, when you downcast in a polymorphic type hierarchy, you should use the following function template.

This function only returns null when the input is null. In debug mode, we use dynamic_cast to double‐check whether the downcast is legal (we die if it's not). In normal mode, we do the efficient static_cast instead. Because the process will die in debug mode, it's important to test to make sure the cast is legal before calling this function!

dynamic_cast should be avoided except as allowed by the style guide (https://google.github.io/styleguide/cppguide.html#Run‐Time_Type_Information__RTTI_).

Use like this: down_cast<T*>(foo);

Return Value

f, downcast to To, or null if f is null.

Note

The return value should not be discarded.

Parameters

Name

Description

f

The source pointer to downcast.

Created with MrDocs