Member Functions of Template Classes: Invocation from Template Functions
In C , a peculiar compilation error arises when attempting to call a member function of a template class from within a template function without explicitly specifying the template keyword. Consider the following code:
template<class X> struct A { template<int I> void f() {} }; template<class T> void g() { A<T> a; a.f<3>(); // Error! }
The compiler encounters an error at Line 18, indicating that the member function's name is not recognized. This is because, as stated in the C Standard (14.2/4), the name of a member template specialization must be prefixed with the template keyword when invoked in certain scenarios.
To rectify the issue, simply modify the code to explicitly include the template keyword:
template<class T> void g() { A<T> a; a.template f<3>(); // Add `template` keyword here }
The updated code compiles successfully because it adheres to the standard's requirement, specifying that the member template's name must be qualified with the template keyword when used in the context of a template function.
The above is the detailed content of Why Do Member Functions of Template Classes Require the `template` Keyword When Called from Template Functions?. For more information, please follow other related articles on the PHP Chinese website!