Home >Backend Development >C++ >Why Does a `const char*` Function Overload Prevail Over a `const char (&)[N]` Template Function?
Question:
Why does a function with a parameter of type const char* take precedence over a function template with a parameter of type const char (&s)[N] when both are equally applicable?
Root Cause:
The ambiguity stems from the relative cost of conversions. Overload resolution favors functions that require less conversion operations. An array is effectively a pointer to its first element, implying that the array-to-pointer conversion costs less than declaring an array-based function template.
Standard Explanation:
According to the C standard ([over.match.best]/(1.3), (1.6)):
In this case:
Possible Workaround:
To prioritize the template-based function, define the second overload as a function template as well:
template <typename T> auto foo(T s) -> std::enable_if_t<std::is_convertible<T, char const*>{}> { std::cout << "raw, size=" << std::strlen(s) << std::endl; }
This partial ordering ensures that the template-based function is selected when applicable.
The above is the detailed content of Why Does a `const char*` Function Overload Prevail Over a `const char (&)[N]` Template Function?. For more information, please follow other related articles on the PHP Chinese website!