[class.conv.fct] (original) (raw)

11 Classes [class]

11.4 Class members [class.mem]

11.4.7 Conversions [class.conv]

11.4.7.2 Conversion functions [class.conv.fct]

A member function of a class X having no parameters with a name of the form

conversion-function-id: operator conversion-type-id

conversion-type-id: type-specifier-seq conversion-declarator

Such functions are called conversion functions.

The type of the conversion function ([dcl.fct]) is “function taking no parameter returningconversion-type-id.

A conversion function is never used to convert a (possibly cv-qualified) object to the (possibly cv-qualified) same object type (or a reference to it), to a (possibly cv-qualified) base class of that type (or a reference to it), or to cv void.106

[ Example

:

struct X { operator int(); operator auto() -> short;
};

void f(X a) { int i = int(a); i = (int)a; i = a; }

In all three cases the value assigned will be converted byX​::​operator int().

end example

]

A conversion function may be explicit ([dcl.fct.spec]), in which case it is only considered as a user-defined conversion for direct-initialization ([dcl.init]).

Otherwise, user-defined conversions are not restricted to use in assignments and initializations.

[ Example

:

class Y { }; struct Z { explicit operator Y() const; };

void h(Z z) { Y y1(z);
Y y2 = z;
Y y3 = (Y)z;
}

void g(X a, X b) { int i = (a) ? 1+a : 0; int j = (a&&b) ? a+b : i; if (a) { } }

end example

]

Theconversion-type-idshall not represent a function type nor an array type.

Theconversion-type-idin aconversion-function-idis the longest sequence of tokens that could possibly form a conversion-type-id.

[ Note

:

This prevents ambiguities between the declarator operator * and its expression counterparts.

[ Example

:

&ac.operator int*i;

The * is the pointer declarator and not the multiplication operator.

end example

]

This rule also prevents ambiguities for attributes.

[ Example

:

operator int [[noreturn]] ();

end example

]

end note

]

Conversion functions are inherited.

Conversion functions can be virtual.

A conversion function template shall not have a deduced return type ([dcl.spec.auto]).

[ Example

:

struct S { operator auto() const { return 10; }
template operator auto() const { return 1.2; }
};

end example

]