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?
, . 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, , .
, Foo, Foo.
main.c . , Foo<int>::foo() .
Foo<int>::foo()
, Foo<int>::foo(). .
, , main.c Foo<int>::foo().
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.
f
Source: https://habr.com/ru/post/1728327/More articles:С#: Распространенность при проверке типа переменной - c#OS X Mac и запись приложения для двух сканирований - objective-cSQL Server 2005 full-text search across multiple tables and columns - sqlWhat kernel does my process work in? - linuxI have a problem with MPMoviePlayerController [iPhone SDK] - iphoneСоздание безопасных вызовов ajax с помощью jQuery - jqueryDo I need to manually delete all events to remove my object from memory? - eventsC # Bitblit from Bitmap for Management (Compact Framework) - c #how to get a stream approved in gdb - xcodeVisual Studio Alt-Copy в Eclipse - eclipseAll Articles