Home > Backend Development > C++ > 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
Release: 2024-11-03 15:58:02
Original
512 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template