Home > Backend Development > C++ > body text

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

Mary-Kate Olsen
Release: 2024-11-02 02:57:30
Original
924 people have browsed it

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

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!