Last updated:2026-10-12
C++ Template Disambiguation¶
1. Background¶
I recently came across this piece of code:
What does the .template here mean?
This section starts from a real example and explores that meaning.
2. template disambiguator¶
In C++, when using dependent names of templates, a template disambiguator is sometimes needed to help the compiler distinguish these names. "Dependent names" are types or values that depend on template parameters, and the compiler cannot determine their exact meaning before the template is instantiated. This can cause the compiler to produce ambiguity when parsing these names.
The template disambiguator uses the keyword "template" to tell the compiler explicitly that a particular name is a template. The compiler can then parse the name correctly, without ambiguity.
The keyword template can only be used with the operators :: (scope resolution), -> (member access through a pointer), and . (member access). The following are all valid examples:
- T::template foo
(); - s.template foo
(); - this->template foo
(); - typename T::template iterator
::value_type v;
Official reference:
Given the code below, what do we get if we leave out .template?
template <typename T>
auto foo_is_not_a_template() {
// ((T::foo) < 34) > (::val())
return T::foo<34>::val();
}
It gets parsed as: ((T::foo) < 34) > (::val())
The corresponding .template example is:
The call is then correctly parsed as a template, foo<34>.
The complete code for this section will be published in the Knowledge Planet; join if you are interested. Thank you!
Related Topics¶
- C++ Pure Virtual Functions and Abstract Classes | C++那些事
- C++ assert | C++那些事
- C++ Bit Fields | C++那些事
- Implementing C++ Polymorphism in C | C++那些事
- C++ const Constants and Qualifiers | C++那些事
- The Complete C++ const Family | C++那些事
- C++ Dereference Operator * | C++那些事
- C++ Initialization and Assignment | C++那些事
- Ways to Return Multiple Values in C++ | C++那些事
- C++ mutable Keyword | C++那些事