Home >Backend Development >C++ >Why Does a `const char*` Function Overload Prevail Over a `const char (&)[N]` Template Function?

Why Does a `const char*` Function Overload Prevail Over a `const char (&)[N]` Template Function?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-26 18:04:08731browse

Why Does a `const char*` Function Overload Prevail Over a `const char (&)[N]` Template Function?

Overloading Conflicts: Pointer Decay vs. Template Deduction

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)):

  • Non-specialized functions are preferred over specialized function templates.
  • If two conversions have the same rank, they are indistinguishable.

In this case:

  • The conversion from an array to a pointer is an Lvalue Transformation with Exact Match rank.
  • Excluding Lvalue Transformations, the conversion rank is not significant.
  • Therefore, neither conversion sequence is better, leading to ambiguity and selection of the char const* overload.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn