"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Published on 2024-11-06
Browse:447

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

template void g()
{
   A a;
   a.template f();  // Explicitly specify 'template' keyword
}

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().

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3