0018 - User-defined Conversion Functions
| Status | Refinement |
|---|---|
| Author | |
| Sponsor |
Implementation Status
| DXC | Clang | |
|---|---|---|
| user-defined conversions | Prototype implementation | Complete |
Introduction
User defined conversion functions are an extremly useful mechanism to allow users to define ways that their objects can be converted from one type to another. This allows for complex data transformations as well as simplified syntaxes for common tasks (like checking validity by casting to bool).
Motivation
HLSL 2021 intended to support user-defined conversion functions, but it was realized after release that the feature did not work, so they were disabled in DXC in April 2026.
This was always a feature the HLSL compiler intended to support, so this proposal codifies it as a supported feature for HLSL 202x.
Proposed solution
HLSL will accept the syntax for defining member functions of the form operator T() where T is any built-in or user-defined type.
User defined conversion functions will be resovled according to the rules in
0003 in explicit cast expressions of the form
(T)Obj and in initialization expressions for built-in types such as T X = Obj where T is a built-in type.
This proposal also will introduce the explicit keyword which may only be
applied to a user-defined conversion function. When a conversion function is
annotated with the explicit keyword the conversion function will be excluded
from any overload set constructed for implicit conversions, allowing the
function to only be resolved in explicit cast expressions.
Detailed Design
Addition to [Lex.Keywords]
The keyword explicit is added to the grammar.
Additions to Function Specifiers [Decl.Spec.Fct]
Editors note:
explicitis added to the grammar formation.
\begin{grammar}
\define{function-specifier}\br
\texttt{export}\br
\texttt{explicit}
\end{grammar}
The explicit specifier may only be used on the declaration of a conversion
function within a class declaration.
Conversion Functions [Class.Conv.Function]
\begin{grammar}
\define{conversion-function-id}\br
\terminal{operator} conversion-type-id\br
\end{grammar}
A member function of a class named as a conversion-function-id specifies a conversion from the class type to the type specified by the conversion-type-id. Such functions are called conversion functions. No return type is specified. The type of the function is a function taking no parameters returning conversion-type-id.
A conversion function may never be used to convert an object to the same type, to a base class of the type, or to void.
The explicit keyword may be applied to a conversion function declaration
(\ref{Decl.Spec.Fct}). Such functions are said to be explicit conversion
functions, which are only considered as a user-defined conversion for
direct-initialization or explicit cast expressions.