Function template not requiring an explicit instantiation when called from instantiated function template

39 Views Asked by At

I have a function template calling another function template. The first one is explicitly instantiated whereas the second one isn't.

I realize that by instantiating the template, a function with the given type is created. But does that mean that any called function template (from within the previous function) is also instantiated?

See the code below to understand what I mean:

main.cpp:


    #include "library.hpp"
    
    int main() {
      std::vector<int> vec = { 1, 2, 3, 4, 5 };
      Library::print_vector(vec);
    
      return 0;
    }

library.hpp:


    #ifndef LIBRARY_HPP
    #define LIBRARY_HPP
    
    #include <vector>
    
    namespace Library {
      template <typename T>
      void print_vector(const std::vector<T>& vec);
    
      template <typename T>
      void print(T x);
    }

library.cpp:

#include <iostream>

#include "library.hpp"

template <typename T>
void Library::print_vector(const std::vector<T>& vec) {
  for (T x : vec)
    print(x);
}

template <typename T>
void Library::print(T x) {
  std::cout << "x: " << x << '\n';
}

// explicit template instantiation
// no template instantiation for Library::print(), and yet no linking error!!!
template void Library::print_vector(const std::vector<int>&);
0

There are 0 best solutions below