13.3.3 Best viable function [over.match.best]

Define ICSi(F) as follows:

• if F is a static member function, ICS1(F) is defined such that ICS1(F) is neither better nor worse than ICS1(G) for any function G, and, symmetrically, ICS1(G) is neither better nor worse than ICS1(F)132; otherwise,

• let ICSi(F) denote the implicit conversion sequence that converts the i-th argument in the list to the type of the i-th parameter of viable function F. [over.best.ics] defines the implicit conversion sequences and [over.ics.rank] defines what it means for one implicit conversion sequence to be a better conversion sequence or worse conversion sequence than another.

Given these definitions, a viable function F1 is defined to be a better function than another viable function F2 if for all arguments i, ICSi(F1) is not a worse conversion sequence than ICSi(F2), and then

• for some argument j, ICSj(F1) is a better conversion sequence than ICSj(F2), or, if not that,

• the context is an initialization by user-defined conversion (see [dcl.init], [over.match.conv], and [over.match.ref]) and the standard conversion sequence from the return type of F1 to the destination type (i.e., the type of the entity being initialized) is a better conversion sequence than the standard conversion sequence from the return type of F2 to the destination type. [ Example:

struct A {
A();
operator int();
operator double();
} a;
int i = a;                      // a.operator int() followed by no conversion
// is better than a.operator double() followed by
// a conversion to int
float x = a;                    // ambiguous: both possibilities require conversions,
// and neither is better than the other

— end example ] or, if not that,

• F1 is a non-template function and F2 is a function template specialization, or, if not that,

• F1 and F2 are function template specializations, and the function template for F1 is more specialized than the template for F2 according to the partial ordering rules described in [temp.func.order].

If there is exactly one viable function that is a better function than all other viable functions, then it is the one selected by overload resolution; otherwise the call is ill-formed133.

Example:

void Fcn(const int*,  short);
void Fcn(int*, int);

int i;
short s = 0;

void f() {
Fcn(&i, s);                   // is ambiguous because
// &i  int* is better than &i  const int*
// but s  short is also better than s  int

Fcn(&i, 1L);                  // calls Fcn(int*, int), because
// &i  int* is better than &i  const int*
// and 1L  short and 1L  int are indistinguishable

Fcn(&i,'c');                  // calls Fcn(int*, int), because
// &i  int* is better than &i  const int*
// and c  int is better than c  short
}

— end example ]

If the best viable function resolves to a function for which multiple declarations were found, and if at least two of these declarations — or the declarations they refer to in the case of using-declarations — specify a default argument that made the function viable, the program is ill-formed. [ Example:

namespace A {
extern "C" void f(int = 5);
}
namespace B {
extern "C" void f(int = 5);
}

using A::f;
using B::f;

void use() {
f(3);                         // OK, default argument was not used for viability
f();                          // Error: found default argument twice
}

— end example ]

If a function is a static member function, this definition means that the first argument, the implied object argument, has no effect in the determination of whether the function is better or worse than any other function.

The algorithm for selecting the best viable function is linear in the number of viable functions. Run a simple tournament to find a function W that is not worse than any opponent it faced. Although another function F that W did not face might be at least as good as W, F cannot be the best function because at some point in the tournament F encountered another function G such that F was not better than G. Hence, W is either the best function or there is no best function. So, make a second pass over the viable functions to verify that W is better than all other functions.

13.3.3.1 Implicit conversion sequences [over.best.ics]

An implicit conversion sequence is a sequence of conversions used to convert an argument in a function call to the type of the corresponding parameter of the function being called. The sequence of conversions is an implicit conversion as defined in Clause [conv], which means it is governed by the rules for initialization of an object or reference by a single expression ([dcl.init], [dcl.init.ref]).

Implicit conversion sequences are concerned only with the type, cv-qualification, and value category of the argument and how these are converted to match the corresponding properties of the parameter. Other properties, such as the lifetime, storage class, alignment, or accessibility of the argument and whether or not the argument is a bit-field are ignored. So, although an implicit conversion sequence can be defined for a given argument-parameter pair, the conversion from the argument to the parameter might still be ill-formed in the final analysis.

A well-formed implicit conversion sequence is one of the following forms:

However, when considering the argument of a constructor or user-defined conversion function that is a candidate by [over.match.ctor] when invoked for the copying/moving of the temporary in the second step of a class copy-initialization, by [over.match.list] when passing the initializer list as a single argument or when the initializer list has exactly one element and a conversion to some class X or reference to (possibly cv-qualified) X is considered for the first parameter of a constructor of X, or by [over.match.copy], [over.match.conv], or [over.match.ref] in all cases, only standard conversion sequences and ellipsis conversion sequences are considered.

For the case where the parameter type is a reference, see [over.ics.ref].

When the parameter type is not a reference, the implicit conversion sequence models a copy-initialization of the parameter from the argument expression. The implicit conversion sequence is the one required to convert the argument expression to a prvalue of the type of the parameter. [ Note: When the parameter has a class type, this is a conceptual conversion defined for the purposes of Clause [over]; the actual initialization is defined in terms of constructors and is not a conversion.  — end note ] Any difference in top-level cv-qualification is subsumed by the initialization itself and does not constitute a conversion. [ Example: a parameter of type A can be initialized from an argument of type const A. The implicit conversion sequence for that case is the identity sequence; it contains no “conversion” from const A to A.  — end example ] When the parameter has a class type and the argument expression has the same type, the implicit conversion sequence is an identity conversion. When the parameter has a class type and the argument expression has a derived class type, the implicit conversion sequence is a derived-to-base Conversion from the derived class to the base class. [ Note: There is no such standard conversion; this derived-to-base Conversion exists only in the description of implicit conversion sequences.  — end note ] A derived-to-base Conversion has Conversion rank ([over.ics.scs]).

In all contexts, when converting to the implicit object parameter or when converting to the left operand of an assignment operation only standard conversion sequences that create no temporary object for the result are allowed.

If no conversions are required to match an argument to a parameter type, the implicit conversion sequence is the standard conversion sequence consisting of the identity conversion ([over.ics.scs]).

If no sequence of conversions can be found to convert an argument to a parameter type or the conversion is otherwise ill-formed, an implicit conversion sequence cannot be formed.

If several different sequences of conversions exist that each convert the argument to the parameter type, the implicit conversion sequence associated with the parameter is defined to be the unique conversion sequence designated the ambiguous conversion sequence. For the purpose of ranking implicit conversion sequences as described in [over.ics.rank], the ambiguous conversion sequence is treated as a user-defined sequence that is indistinguishable from any other user-defined conversion sequence134. If a function that uses the ambiguous conversion sequence is selected as the best viable function, the call will be ill-formed because the conversion of one of the arguments in the call is ambiguous.

The three forms of implicit conversion sequences mentioned above are defined in the following subclauses.

The ambiguous conversion sequence is ranked with user-defined conversion sequences because multiple conversion sequences for an argument can exist only if they involve different user-defined conversions. The ambiguous conversion sequence is indistinguishable from any other user-defined conversion sequence because it represents at least two user-defined conversion sequences, each with a different user-defined conversion, and any other user-defined conversion sequence must be indistinguishable from at least one of them.

This rule prevents a function from becoming non-viable because of an ambiguous conversion sequence for one of its parameters. Consider this example,

class B;
class A { A (B&);};
class B { operator A (); };
class C { C (B&); };
void f(A) { }
void f(C) { }
B b;
f(b);	// ambiguous because b  C via constructor and// b  A via constructor or conversion function.

If it were not for this rule, f(A) would be eliminated as a viable function for the call f(b) causing overload resolution to select f(C) as the function to call even though it is not clearly the best choice. On the other hand, if an f(B) were to be declared then f(b) would resolve to that f(B) because the exact match with f(B) is better than any of the sequences required to match f(A).

13.3.3.1.1 Standard conversion sequences [over.ics.scs]

Table [tab:over.conversions] summarizes the conversions defined in Clause [conv] and partitions them into four disjoint categories: Lvalue Transformation, Qualification Adjustment, Promotion, and Conversion. [ Note: These categories are orthogonal with respect to value category, cv-qualification, and data representation: the Lvalue Transformations do not change the cv-qualification or data representation of the type; the Qualification Adjustments do not change the value category or data representation of the type; and the Promotions and Conversions do not change the value category or cv-qualification of the type.  — end note ]

Note: As described in Clause [conv], a standard conversion sequence is either the Identity conversion by itself (that is, no conversion) or consists of one to three conversions from the other four categories. At most one conversion from each category is allowed in a single standard conversion sequence. If there are two or more conversions in the sequence, the conversions are applied in the canonical order: Lvalue Transformation, Promotion or Conversion, Qualification Adjustment.  — end note ]

Each conversion in Table [tab:over.conversions] also has an associated rank (Exact Match, Promotion, or Conversion). These are used to rank standard conversion sequences ([over.ics.rank]). The rank of a conversion sequence is determined by considering the rank of each conversion in the sequence and the rank of any reference binding ([over.ics.ref]). If any of those has Conversion rank, the sequence has Conversion rank; otherwise, if any of those has Promotion rank, the sequence has Promotion rank; otherwise, the sequence has Exact Match rank.

Table 12 — Conversions
 Conversion Category Rank Subclause No conversions required Identity Lvalue-to-rvalue conversion [conv.lval] Array-to-pointer conversion Lvalue Transformation Exact Match [conv.array] Function-to-pointer conversion [conv.func] Qualification conversions Qualification Adjustment [conv.qual] Integral promotions [conv.prom] Floating point promotion Promotion Promotion [conv.fpprom] Integral conversions [conv.integral] Floating point conversions [conv.double] Floating-integral conversions [conv.fpint] Pointer conversions Conversion Conversion [conv.ptr] Pointer to member conversions [conv.mem] Boolean conversions [conv.bool]

13.3.3.1.2 User-defined conversion sequences [over.ics.user]

A user-defined conversion sequence consists of an initial standard conversion sequence followed by a user-defined conversion ([class.conv]) followed by a second standard conversion sequence. If the user-defined conversion is specified by a constructor ([class.conv.ctor]), the initial standard conversion sequence converts the source type to the type required by the argument of the constructor. If the user-defined conversion is specified by a conversion function ([class.conv.fct]), the initial standard conversion sequence converts the source type to the implicit object parameter of the conversion function.

The second standard conversion sequence converts the result of the user-defined conversion to the target type for the sequence. Since an implicit conversion sequence is an initialization, the special rules for initialization by user-defined conversion apply when selecting the best user-defined conversion for a user-defined conversion sequence (see [over.match.best] and [over.best.ics]).

If the user-defined conversion is specified by a specialization of a conversion function template, the second standard conversion sequence shall have exact match rank.

A conversion of an expression of class type to the same class type is given Exact Match rank, and a conversion of an expression of class type to a base class of that type is given Conversion rank, in spite of the fact that a copy/move constructor (i.e., a user-defined conversion function) is called for those cases.

13.3.3.1.3 Ellipsis conversion sequences [over.ics.ellipsis]

An ellipsis conversion sequence occurs when an argument in a function call is matched with the ellipsis parameter specification of the function called (see [expr.call]).

13.3.3.1.4 Reference binding [over.ics.ref]

When a parameter of reference type binds directly ([dcl.init.ref]) to an argument expression, the implicit conversion sequence is the identity conversion, unless the argument expression has a type that is a derived class of the parameter type, in which case the implicit conversion sequence is a derived-to-base Conversion ([over.best.ics]). [ Example:

struct A {};
struct B : public A {} b;
int f(A&);
int f(B&);
int i = f(b);                   // calls f(B&), an exact match, rather than
// f(A&), a conversion

— end example ] If the parameter binds directly to the result of applying a conversion function to the argument expression, the implicit conversion sequence is a user-defined conversion sequence ([over.ics.user]), with the second standard conversion sequence either an identity conversion or, if the conversion function returns an entity of a type that is a derived class of the parameter type, a derived-to-base Conversion.

When a parameter of reference type is not bound directly to an argument expression, the conversion sequence is the one required to convert the argument expression to the underlying type of the reference according to [over.best.ics]. Conceptually, this conversion sequence corresponds to copy-initializing a temporary of the underlying type with the argument expression. Any difference in top-level cv-qualification is subsumed by the initialization itself and does not constitute a conversion.

Except for an implicit object parameter, for which see [over.match.funcs], a standard conversion sequence cannot be formed if it requires binding an lvalue reference other than a reference to a non-volatile const type to an rvalue or binding an rvalue reference to an lvalue other than a function lvalue. [ Note: This means, for example, that a candidate function cannot be a viable function if it has a non-const lvalue reference parameter (other than the implicit object parameter) and the corresponding argument is a temporary or would require one to be created to initialize the lvalue reference (see [dcl.init.ref]).  — end note ]

Other restrictions on binding a reference to a particular argument that are not based on the types of the reference and the argument do not affect the formation of a standard conversion sequence, however. [ Example: a function with an “lvalue reference to int” parameter can be a viable candidate even if the corresponding argument is an int bit-field. The formation of implicit conversion sequences treats the int bit-field as an int lvalue and finds an exact match with the parameter. If the function is selected by overload resolution, the call will nonetheless be ill-formed because of the prohibition on binding a non-const lvalue reference to a bit-field ([dcl.init.ref]).  — end example ]

The binding of a reference to an expression that is reference-compatible with added qualification influences the rank of a standard conversion; see [over.ics.rank] and [dcl.init.ref].

13.3.3.1.5 List-initialization sequence [over.ics.list]

When an argument is an initializer list ([dcl.init.list]), it is not an expression and special rules apply for converting it to a parameter type.

If the parameter type is std::initializer_list<X> or “array of X135 and all the elements of the initializer list can be implicitly converted to X, the implicit conversion sequence is the worst conversion necessary to convert an element of the list to X. This conversion can be a user-defined conversion even in the context of a call to an initializer-list constructor. [ Example:

void f(std::initializer_list<int>);
f( {1,2,3} );               // OK: f(initializer_list<int>) identity conversion
f( {'a','b'} );             // OK: f(initializer_list<int>) integral promotion
f( {1.0} );                 // error: narrowing

struct A {
A(std::initializer_list<double>);           // #1
A(std::initializer_list<complex<double>>);  // #2
A(std::initializer_list<std::string>);      // #3
};
A a{ 1.0,2.0 };             // OK, uses #1

void g(A);
g({ "foo", "bar" });        // OK, uses #3

typedef int IA;
void h(const IA&);
h({ 1, 2, 3 });             // OK: identity conversion

— end example ]

Otherwise, if the parameter is a non-aggregate class X and overload resolution per [over.match.list] chooses a single best constructor of X to perform the initialization of an object of type X from the argument initializer list, the implicit conversion sequence is a user-defined conversion sequence. If multiple constructors are viable but none is better than the others, the implicit conversion sequence is the ambiguous conversion sequence. User-defined conversions are allowed for conversion of the initializer list elements to the constructor parameter types except as noted in [over.best.ics]. [ Example:

struct A {
A(std::initializer_list<int>);
};
void f(A);
f( {'a', 'b'} );            // OK: f(A(std::initializer_list<int>)) user-defined conversion

struct B {
B(int, double);
};
void g(B);
g( {'a', 'b'} );            // OK: g(B(int,double)) user-defined conversion
g( {1.0, 1,0} );            // error: narrowing

void f(B);
f( {'a', 'b'} );            // error: ambiguous f(A) or f(B)

struct C {
C(std::string);
};
void h(C);
h({"foo"});                 // OK: h(C(std::string("foo")))

struct D {
C(A, C);
};
void i(D);
i({ {1,2}, {"bar"} });      // OK: i(D(A(std::initializer_list<int>{1,2}),C(std::string("bar"))))

— end example ]

Otherwise, if the parameter has an aggregate type which can be initialized from the initializer list according to the rules for aggregate initialization ([dcl.init.aggr]), the implicit conversion sequence is a user-defined conversion sequence. [ Example:

struct A {
int m1;
double m2;
};

void f(A);
f( {'a', 'b'} );            // OK: f(A(int,double)) user-defined conversion
f( {1.0} );                 // error: narrowing

— end example ]

Otherwise, if the parameter is a reference, see [over.ics.ref]. [ Note: The rules in this section will apply for initializing the underlying temporary for the reference.  — end note ] [ Example:

struct A {
int m1;
double m2;
};

void f(const A&);
f( {'a', 'b'} );            // OK: f(A(int,double)) user-defined conversion
f( {1.0} );                 // error: narrowing

void g(const double &);
g({1});                     // same conversion as int to double

— end example ]

Otherwise, if the parameter type is not a class:

• if the initializer list has one element, the implicit conversion sequence is the one required to convert the element to the parameter type; [ Example:

void f(int);
f( {'a'} );                 // OK: same conversion as char to int
f( {1.0} );                 // error: narrowing

— end example ]

• if the initializer list has no elements, the implicit conversion sequence is the identity conversion. [ Example:

void f(int);
f( { } );                   // OK: identity conversion

— end example ]

In all cases other than those enumerated above, no conversion is possible.

Since there are no parameters of array type, this will only occur as the underlying type of a reference parameter.

13.3.3.2 Ranking implicit conversion sequences [over.ics.rank]

[over.ics.rank] defines a partial ordering of implicit conversion sequences based on the relationships better conversion sequence and better conversion. If an implicit conversion sequence S1 is defined by these rules to be a better conversion sequence than S2, then it is also the case that S2 is a worse conversion sequence than S1. If conversion sequence S1 is neither better than nor worse than conversion sequence S2, S1 and S2 are said to be indistinguishable conversion sequences.

When comparing the basic forms of implicit conversion sequences (as defined in [over.best.ics])

• a standard conversion sequence ([over.ics.scs]) is a better conversion sequence than a user-defined conversion sequence or an ellipsis conversion sequence, and

• a user-defined conversion sequence ([over.ics.user]) is a better conversion sequence than an ellipsis conversion sequence ([over.ics.ellipsis]).

Two implicit conversion sequences of the same form are indistinguishable conversion sequences unless one of the following rules applies:

• Standard conversion sequence S1 is a better conversion sequence than standard conversion sequence S2 if

• S1 is a proper subsequence of S2 (comparing the conversion sequences in the canonical form defined by [over.ics.scs], excluding any Lvalue Transformation; the identity conversion sequence is considered to be a subsequence of any non-identity conversion sequence) or, if not that,

• the rank of S1 is better than the rank of S2, or S1 and S2 have the same rank and are distinguishable by the rules in the paragraph below, or, if not that,

• S1 and S2 differ only in their qualification conversion and yield similar types T1 and T2 ([conv.qual]), respectively, and the cv-qualification signature of type T1 is a proper subset of the cv-qualification signature of type T2. [ Example:

int f(const int *);
int f(int *);
int i;
int j = f(&i);                  // calls f(int*)

— end example ] or, if not that,

• S1 and S2 are reference bindings ([dcl.init.ref]) and neither refers to an implicit object parameter of a non-static member function declared without a ref-qualifier, and S1 binds an rvalue reference to an rvalue and S2 binds an lvalue reference.

Example:

int i;
int f1();
int&& f2();
int g(const int&);
int g(const int&&);
int j = g(i);                   // calls g(const int&)
int k = g(f1());                // calls g(const int&&)
int l = g(f2());                // calls g(const int&&)

struct A {
A& operator<<(int);
void p() &;
void p() &&;
};
A& operator<<(A&&, char);
A() << 1;                       // calls A::operator<<(int)
A() << 'c';                     // calls operator<<(A&&, char)
A a;
a << 1;                         // calls A::operator<<(int)
a << 'c';                       // calls A::operator<<(int)
A().p();                        // calls A::p()&&
a.p();                          // calls A::p()&

— end example ] or, if not that,

• S1 and S2 are reference bindings ([dcl.init.ref]) and S1 binds an lvalue reference to a function lvalue and S2 binds an rvalue reference to a function lvalue. [ Example:

template<class T> int f(T&);
template<class T> int f(T&&);
void g();
int i1 = f(g);                  // calls f(T&)

— end example ]

• S1 and S2 are reference bindings ([dcl.init.ref]), and the types to which the references refer are the same type except for top-level cv-qualifiers, and the type to which the reference initialized by S2 refers is more cv-qualified than the type to which the reference initialized by S1 refers. [ Example:

int f(const int &);
int f(int &);
int g(const int &);
int g(int);

int i;
int j = f(i);                   // calls f(int &)
int k = g(i);                   // ambiguous

struct X {
void f() const;
void f();
};
void g(const X& a, X b) {
a.f();                        // calls X::f() const
b.f();                        // calls X::f()
}

— end example ]

• User-defined conversion sequence U1 is a better conversion sequence than another user-defined conversion sequence U2 if they contain the same user-defined conversion function or constructor or aggregate initialization and the second standard conversion sequence of U1 is better than the second standard conversion sequence of U2. [ Example:

struct A {
operator short();
} a;
int f(int);
int f(float);
int i = f(a);                   // calls f(int), because short  int is
// better than short  float.

— end example ]

• List-initialization sequence L1 is a better conversion sequence than list-initialization sequence L2 if L1 converts to std::initializer_list<X> for some X and L2 does not.

Standard conversion sequences are ordered by their ranks: an Exact Match is a better conversion than a Promotion, which is a better conversion than a Conversion. Two conversion sequences with the same rank are indistinguishable unless one of the following rules applies:

• A conversion that does not convert a pointer, a pointer to member, or std::nullptr_t to bool is better than one that does.

• If class B is derived directly or indirectly from class A, conversion of B* to A* is better than conversion of B* to void*, and conversion of A* to void* is better than conversion of B* to void*.

• If class B is derived directly or indirectly from class A and class C is derived directly or indirectly from B,

• conversion of C* to B* is better than conversion of C* to A*, [ Example:

struct A {};
struct B : public A {};
struct C : public B {};
C *pc;
int f(A *);
int f(B *);
int i = f(pc);                  // calls f(B*)

— end example ]

• binding of an expression of type C to a reference of type B& is better than binding an expression of type C to a reference of type A&,

• conversion of A::* to B::* is better than conversion of A::* to C::*,

• conversion of C to B is better than conversion of C to A,

• conversion of B* to A* is better than conversion of C* to A*,

• binding of an expression of type B to a reference of type A& is better than binding an expression of type C to a reference of type A&,

• conversion of B::* to C::* is better than conversion of A::* to C::*, and

• conversion of B to A is better than conversion of C to A.

Note: Compared conversion sequences will have different source types only in the context of comparing the second standard conversion sequence of an initialization by user-defined conversion (see [over.match.best]); in all other contexts, the source types will be the same and the target types will be different.  — end note ]