How can I implement the template function in the .cpp file ?
function.h
class f{
void f1();
template<typename T>
void f3(std::vector<T> &){
//Implementation
}
}
function.cpp
void f::f1(){
//code
}
How can I implement the template function in the .cpp file ?
function.h
class f{
void f1();
template<typename T>
void f3(std::vector<T> &){
//Implementation
}
}
function.cpp
void f::f1(){
//code
}
The following should work. I fixed the syntax and removed the f3 definition from the header file. Also, by default a class
access specifier is private
so accessing f3(std::vector<T>&)
from main would be illegal.
See also Jarod42's answer about implementing templates in the header.
//function.h
#include <vector>
class F {
public:
void f1();
template<typename T>
void f3(std::vector<T> &);
};
#include "function.tpp"
//function.tpp
template<typename T>
void F::f3(std::vector<T> &){
//Implementation
}
//main.cc
int main() {
std::vector<int> v;
F f;
f.f3(v);
}
Simply:
// function.cpp
template<typename T>
void f::f3(std::vector<T> &){
//Implementation
}
But see Why can templates only be implemented in the header file?
If you have template method its definition must be visible in place where template is instantiated. This means that in 99% of cases template definition must be in header file.
There is a way to workaround it in special cases. You can force instantiation of template for specific type, by listing this types in cpp file. In such case you will be limited to only this specific types.
foo.h
#include <vector>
class f{
public:
void f1();
template<typename T>
void f3(std::vector<T> &);
};
foo.cpp
#include "foo.h"
#include <iostream>
#define LOG std::cout << __PRETTY_FUNCTION__ << '\n'
void f::f1()
{
LOG;
}
template<typename T>
void f::f3(std::vector<T> &)
{
LOG;
}
template void f::f3<int>(std::vector<int> &);
template void f::f3<double>(std::vector<double> &);
main.cpp
#include "foo.h"
#include <iostream>
int main()
{
std::vector<int> bar{ 1, 3, 5, 6 };
f foo;
foo.f1();
foo.f3(bar);
return 0;
}
Note new C++ feature is coming. In C++20 modules are introduced. Simply no more header files.