7/25/2025

Understanding C++ Templates, (class, member function and this)

 

template<int INT>
void AAA() {
std::cout << "INT = " << INT << std::endl;
}

How to Call It:

Normal Context (Outside Class):

AAA<2>(); // ✅ Just call directly
AAA<5>(); // ✅ Works fine
AAA<10>(); // ✅ No problem

Inside Template Class Context:

template<typename T>
class MyClass {
template<int INT>
void AAA() {
std::cout << "INT = " << INT << std::endl;
}

void some_function() {
// WRONG:
template AAA<2>(); // ❌ ERROR! Invalid syntax

// CORRECT:
this->template AAA<2>(); // ✅ Works!
AAA<2>(); // ✅ Usually works too
}
};

Key Point:

- template AAA<2>(); is INVALID C++ syntax
- this->template AAA<2>(); is VALID C++ syntax

The Rule:

- template keyword only goes after -> or . in template contexts
- You cannot start a statement with just template

Correct Examples:

this->template AAA<2>(); // ✅ In class context
obj.template AAA<2>(); // ✅ With object
ptr->template AAA<2>(); // ✅ With pointer
AAA<2>(); // ✅ Direct call (no template keyword needed)

No comments:

Post a Comment