Home  >  Article  >  Backend Development  >  Why Does Template Member Function Invocation Within a Template Function Fail in C ?

Why Does Template Member Function Invocation Within a Template Function Fail in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-02 02:57:30925browse

Why Does Template Member Function Invocation Within a Template Function Fail in C  ?

Template Member Function Invocation within Template Function

In the given code, an attempt to invoke a template member function f within a template function g fails with compilation errors:

<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 (Line 18)
}</code>

According to the C Standard (14.2/4), when a member template specialization is called after a ., the template keyword must be explicitly specified to differentiate it from a non-template member function.

To resolve the compilation error, the code should be modified as follows:

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

By adding the template keyword, the compiler recognizes that the invoked function is a member template specialization, resolving the ambiguity and allowing the code to compile successfully.

The above is the detailed content of Why Does Template Member Function Invocation Within a Template Function Fail 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