Home  >  Article  >  Backend Development  >  Why Does Invoking a Member Function Template from a Templated Function Require the `template` Keyword?

Why Does Invoking a Member Function Template from a Templated Function Require the `template` Keyword?

Linda Hamilton
Linda HamiltonOriginal
2024-11-03 15:58:02429browse

Why Does Invoking a Member Function Template from a Templated Function Require the `template` Keyword?

Member Function of Templated Class Invocation from Templated Function

In the provided code snippet, invoking a member function template from within another template results in a compilation error. Specifically, the code attempts to call A::f<3>() from within g(). However, this fails due to a syntax issue.

To resolve this, the template keyword must be explicitly specified before the member function invocation. This is because according to the C '03 Standard 14.2/4, when the name of a member template specialization appears after a postfix-expression or qualified-id that depends on a template parameter, the member template name must be prefixed with the template keyword.

Therefore, the following code is correct:

<code class="cpp">template<class T> void g()
{
   A<T> a;
   a.template f<3>();  // Explicitly specify 'template' keyword
}</code>

By adding the template keyword, the compiler can correctly identify that f is a member template of the A class template, and it can successfully call A::f<3>().

The above is the detailed content of Why Does Invoking a Member Function Template from a Templated Function Require the `template` Keyword?. 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