Home >Backend Development >C++ >Why does the compiler fail to compile when invoking a template member function within a template function?

Why does the compiler fail to compile when invoking a template member function within a template function?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-02 16:08:29768browse

Why does the compiler fail to compile when invoking a template member function within a template function?

Template Member Function Invocation within Template Functions

The code snippet provided demonstrates an error encountered when invoking a template member function from within a template function:

<code class="cpp">template<class X> struct A {
   template<int I> void f() {}
};

template<class T> void g()
{
   A<T> a;
   a.f<3>();  // Compilation fails here
}</code>

The compiler fails to compile this code, reporting an error related to an invalid use of member and suggesting that '&' might have been forgotten.

Explanation

The error occurs because the code attempts to invoke a member template without explicitly specifying the 'template' keyword before it. According to the C Standard (14.2/4), when the name of a member template specialization is used after a dot or arrow in a postfix expression, or after a nested-name-specifier in a qualified-id, and the postfix-expression or qualified-id explicitly depends on a template-parameter, the member template name must be prefixed by the keyword 'template.' Otherwise, the name will be assumed to refer to a non-template.

Solution

To resolve this issue, the code must be modified to explicitly specify the 'template' keyword before the member template name:

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

With this modification, the compiler will be able to correctly identify and invoke the member template function, and the code will compile successfully.

The above is the detailed content of Why does the compiler fail to compile when invoking a template member function within a 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