Apart from this, You should also read: using extern template (C++11)
To defer instantiation using extern
, you must match the function signature exactly, so below will not work unless T
is defined as std::vector<int>
or its alias - which matches your template declaration.:
extern template std::ostream & cprint<std::vector<int>>
(T &t, std::string msg = "Container", std::ostream & stream = cout);
To fix,
extern template std::ostream& cprint<std::vector<int>>
(std::vector<int>&, std::string msg = "Container", std::ostream & stream = cout);
See it Here
More concretely,
In Header.hpp file, I have its declaration and its deferment:
template <typename T>
std::ostream & cprint(T &t, std::string msg = "Container", std::ostream & stream = cout){
stream << msg << "\t{ ";
for(typename T::iterator it = t.begin(); it != t.end(); it++)
stream << *it << " ";
stream << "}\n";
return stream;
}
//defer instantiation
extern template std::ostream& cprint<std::vector<int>>
(std::vector<int>&, std::string msg = "Container", std::ostream & stream = cout);
Now, in main.cpp file, I have:
int main(){
std::vector<int> v{1, 2, 3, 4, 5};
cprint(v);
}
In the Header.cpp file, I have its instantiation:
template std::ostream& cprint<std::vector<int>>
(std::vector<int>&, std::string msg = "Container", std::ostream & stream = cout);
As seen Here
=====================
EDIT: With respect to your recent edit:
Edit: assume other.cpp has a basic function as below,
template <typename T>
void func(T x){
cout << x << endl;
}
how to instantiate this function in main.cpp?
If the translation unit, main.cpp sees the declaration of the function template func
(either from an included header, or you (re-(forward-))declared it in main.cpp, it will compile as calling a function template-specialization1, but the linker will be unable to find the function template-specialization unless it sees the definition of that function template-specialization as instantiated in (another) translation unit.
Note: "function template specialization" is a function instantiated from a function template. See temp.fct/1