Multiple Viable Templates

As another example, consider the following call:

const string *sp = &s;
cout << debug_rep(sp) << endl;

Here both templates are viable and both provide an exact match:

debug_rep(const string* &), the instantiation of the first version of the template with T bound to const string*

debug_rep(const string*), the instantiation of the second version of the template with T bound to const string

In this case, normal function matching can’t distinguish between these two calls. We might expect this call to be ambiguous. However, due to the special rule for overloaded function templates, this call resolves to debug_rep(T*), which is the more specialized template.

The reason for this rule is that without it, there would be no way to call the pointer version of debug_rep on a pointer to const. The problem is that the template debug_rep(const T&) can be called on essentially any type, including pointer types. That template is more general than debug_rep(T*), which can be called only on pointer types. Without this rule, calls that passed pointers to const would always be ambiguous.


Image Note

When there are several overloaded templates that provide an equally good match for a call, the most specialized version is preferred.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.234.188