Home >Backend Development >C++ >Why Does Argument Dependent Lookup Fail to Find Function Templates with Explicit Template Arguments in C ?

Why Does Argument Dependent Lookup Fail to Find Function Templates with Explicit Template Arguments in C ?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-09 05:42:10915browse

Why Does Argument Dependent Lookup Fail to Find Function Templates with Explicit Template Arguments in C  ?

Argument Dependent Lookup and Function Templates in C

Argument dependent lookup (ADL) is a language feature that enables the compiler to search for identifiers within the namespaces associated with the arguments of a function call. While ADL typically finds functions, it fails to find function templates in some scenarios.

The C Standard Explanation

Section 14.8.1.6 of the C Standard (2003) states that:

"But when a function template with explicit template arguments is used, the call does not have the correct syntactic form unless there is a function template with that name visible at the point of the call. If no such name is visible, the call is not syntactically well-formed and argument-dependent lookup does not apply."

Example

Consider the following example:

namespace ns {
    struct foo {};
    template<int i> void frob(foo const&amp;) {}
    void non_template(foo const&amp;) {}
}

int main() {
    ns::foo f;
    non_template(f); // This is fine.
    frob<0>(f); // This is not.
}

The last call in main (frob<0>(f);) fails to compile because no function template with the name frob is visible in the scope of the call. ADL cannot find frob<0> because function templates are not considered valid function calls by the compiler's syntax.

Additional Considerations

  • For simple function names (without template arguments), ADL can still find function templates even if their names are not visible.
  • However, if the function template is called with explicit template arguments, a function template with that specific name must be visible in the scope of the call for ADL to succeed.
  • In some cases, using declarations can make a function template visible, allowing ADL to find it.

The above is the detailed content of Why Does Argument Dependent Lookup Fail to Find Function Templates with Explicit Template Arguments in C ?. 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