I'm learning about templates in c++ and I found the following example.
From what I understand, the compiler should always try to use the most "specialized" template if there is no non-template functions matching, yet in this example, the first call result in calling function a(T*) instead of a(int*). Why? And why does second call act differently?
template<typename T> void a(T) {cout << "(T)" << endl;} template<> void a<>(int*) {cout << "(int)" << endl;} template<typename T> void a(T*) {cout << "(T*)" << endl;} template<typename T> void b(T) {cout << "(T)" << endl;} template<typename T> void b(T*) {cout << "(T*)" << endl;} template<> void b<>(int*) {cout << "(int)" << endl;} int main() { int i; a(&i); b(&i); return 0; }
The resulting output is:
(T*)
(int)
I expected it to be:
(int)
(int)
If you want to find out which template is attached to a document, you can do so by displaying the Developer tab of the ribbon and then clicking on the Document Template tool. Word displays the Templates and Add-ins dialog box.
Templates are pre-formatted documents, intended to speed up the creation of commonly used document types such as letters, fax forms, or envelopes. Templates are also used as guidelines for creating documents in a specific format (for example, the required format for submitting a paper to a scientific journal).
Go to C:\Users\user name\AppData\Roaming\Microsoft\Templates. Open the Normal template (Normal. dotm).
Only primary templates (so no specializations) are taken into account to select more specialized overloads.
Once selection is done with primary template, we use the specialization if any.
Now, template<> void a<>(int*);
can only be specialization of template<typename T> void a(T)
(the other version has not been seen).
and template<> void b<>(int*);
is specialization of template<typename T> void b(T*)
(it is the more specialized matching overloads).
Notice that you might select specialization of b
by providing template instead of letting compiler deduce:
template<> void b<>(int*)
-> template<typename T> void b(T*) with T=int
template<> void b<int>(int*)
-> template<typename T> void b(T*) with T=int
template<> void b<int*>(int*)
-> template<typename T> void b(T) with T=int*
so for:
int i;
a(&i); // a<T*> with T=int*, no specialization for a<U*> (U=int) exist -> generic template called
b(&i); // b<T*> with T=int*, specialization for b<U*> (U=int) exists -> specialization called
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With