Reputation: 79
In VS 2013 , I declared a function in a header file named "util_serial.h" and defined it in the cpp file named "util_serial.cpp", like this:
util_serial.h :
#ifndef _UTIL_SERIAL_H_
#define _UTIL_SERIAL_H_
template<typename T> inline std::vector<T> slice_vec(std::vector<T>& vec, int _begin, int len);
#endif
util_serial.cpp :
#include "util_serial.h"
using namespace std;
template<typename T> inline std::vector<T> slice_vec(vector<T>& vec, int _begin, int len) {
if (_begin < 0) {
_begin = 0;
}
if (vec.size() < _begin) {
vector<T> v;
printf("slicing out of the vector range\n");
return v;
}
if (vec.size() < _begin + len) {
vector<T> v(vec.begin() + _begin, vec.end());
return v;
}
else {
vector<T> v(vec.begin() + _begin, vec.begin() + _begin + len);
return v;
}
}
Then I call this function in main function at another cpp file :
#include "util_serial.h"
using namespace std;
void main() {
vector<int> v3(4, 8);
vector<int> v4;
v4 = slice_vec(v3, 0, 2);
for (unsigned int i = 0; i < v4.size(); i++) {
cout << v4[i] << endl;
}
}
And then a LINK error occurred:
But when I define this function in the util_serial.h file right there after the declaration, this error disappeared.
This is what I used to do, declaring a function in a header file and putting its definition in another cpp file and it always works. But why this time it doesn't ?
Upvotes: 0
Views: 308
Reputation: 16781
That's how templates work. If you don't put the template function into the header file you need to explicitely instantiate the function for the type(s) that you need.
template std::vector<int> slice_vec<int>(std::vector<int>& vec, int _begin, int len);
See also How do I explicitly instantiate a template function?.
Upvotes: 1