How does the compiler know to use template specialization instead of its own instance?

Consider the following files:

foo.h

template <typename T>
struct Foo
{
  int foo();
};

template <typename T>
int Foo<T>::foo()
{
  return 6;
}

Foo.c

#include "Foo.H"

template <>
int Foo<int>::foo()
{
  return 7;
}

main.c

#include <iostream>
#include "Foo.H"

using namespace std;

int main()
{
  Foo<int> f;
  cout << f.foo() << endl;
  return 0;
}

When I compile and run, it prints 7. What is happening here? When are templates created? If the compiler does this, how does the compiler know not to create its own version of Foo?

+3
source share
4 answers

, . main.C Foo.H, Foo.C( , ). main.C , , Foo.C, ( 6) Foo. , Foo.C, , - , -, ( , ), Foo.

. " ", , . , , (, , , ).

? Foo , , , Foo , . , . , (foo.C), (main.C).

Foo.H, main.C Foo, , .

+17

, Foo, Foo.

+2

main.c . , Foo<int>::foo() .

, Foo<int>::foo(). .

, , main.c Foo<int>::foo().

+1

Templates generate different classes for each combination of template parameters. This happens at compile time, and for this very reason templates should be in the headers. You do specialization for the int parameter, and the compiler calls Foo<int>::foo()for your variable f. This is similar to canceling a virtual function, but at compile time.

-2
source

Source: https://habr.com/ru/post/1728327/


All Articles