0

Starting to learn C++, I fell on this -

If I created a class template/function template I need to know in advance possible "types" that may use it. So I need to declare something like :

class template ClassName<type1,type2>;

The line above causes a specialization to be instantiated for specific function and linker attaches calls to that instance. But then question is how STL containers/algorithms etc achieve that for "any" user object?

Seems like this has to do with interface of application.

Excuse me if this is a duplicate question but I did not find any answer on google or StackOverflow. If it is already there, a pointer would help.

  • 2
    If you're referring to an [explicit instantiation](https://stackoverflow.com/questions/2351148/explicit-template-instantiation-when-is-it-used), it is not required, and is actually fairly rare. – chris May 25 '21 at 05:54
  • Perhaps reading this could make it clear [Why can templates only be implemented in the header file?](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – 273K May 25 '21 at 05:54
  • @S.M. I read that, and from such articles only I learnt about that declaration. It was said that when you have template class definition separated from implementation, we need this. Does this mean, that whole STL container is written in headers? If possible please let me know how they interface it with user applications? Thank you. – CalmStudent May 25 '21 at 06:09
  • _"emplate/function template I need to know in advance possible "types" that may use it"_ - no, most of the time you don't (and can't). That's the point of templates, you define them once (in a header usually) and it's automatically instantiated for all types you want to use it with. – Lukas-T May 25 '21 at 06:10
  • Yes the standard library containers are completely defined in the header files, they may have some helper non-template classes implemented in cpp files – Alan Birtles May 25 '21 at 06:18
  • @AlanBirtles Thanks, so when I used std::vector, it will compile not just my code but code for std::vector as well. Then i should be able to see the code for it. If possible, please let me know where is it for gcc and msvc. – CalmStudent May 25 '21 at 09:01
  • just do "go to declaration" or the equivalent in your favourite IDE to see the implementation – Alan Birtles May 25 '21 at 09:25

0 Answers0