Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine which template will be used

Tags:

c++

templates

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)
like image 440
Aileen Avatar asked Jun 06 '19 08:06

Aileen


People also ask

How do I know which template to use in Word?

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.

What are the templates when are they used?

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).

How do I find my normal template?

Go to C:\Users\user name\AppData\Roaming\Microsoft\Templates. Open the Normal template (Normal. dotm).


1 Answers

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
like image 78
Jarod42 Avatar answered Nov 15 '22 12:11

Jarod42