absl::implicit_cast

Performs an implicit conversion between types following the language rules for implicit conversion; if an implicit conversion is otherwise allowed by the language in the given context, this function performs such an implicit conversion.

Synopsis

Declared in <absl/base/casts.h>

template<typename To>
constexpr
To
implicit_cast(To to)
requires !type_traits_internal::IsView<std::enable_if_t<
        !std::is_reference_v<To>, std::remove_cv_t<To>>>::value;

Description

Example:

// If the context allows implicit conversion: From from; To to = from;

// Such code can be replaced by: implicit_cast<To>(from);

An implicit_cast() may also be used to annotate numeric type conversions that, although safe, may produce compiler warnings (such as long to int). Additionally, an implicit_cast() is also useful within return statements to indicate a specific implicit conversion is being undertaken.

Example:

return implicit_cast<double>(size_in_bytes) / capacity_;

Annotating code with implicit_cast() allows you to explicitly select particular overloads and template instantiations, while providing a safer cast than reinterpret_cast() or static_cast().

Additionally, an implicit_cast() can be used to allow upcasting within a type hierarchy where incorrect use of static_cast() could accidentally allow downcasting.

Finally, an implicit_cast() can be used to perform implicit conversions from unrelated types that otherwise couldn't be implicitly cast directly; C++ will normally only implicitly cast "one step" in such conversions.

That is, if C is a type which can be implicitly converted to B, with B being a type that can be implicitly converted to A, an implicit_cast() can be used to convert C to B (which the compiler can then implicitly convert to A using language rules).

Example:

// Assume an object C is convertible to B, which is implicitly convertible // to A A a = implicit_cast<B>(C);

Such implicit cast chaining may be useful within template logic. This overload participates in overload resolution when To is not a view type and not a reference type.

Return Value

The value of to, converted to To.

Parameters

NameDescription
toThe value to convert to To.