0

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: Error List

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 ?

Community
  • 1
  • 1
Zhang
  • 79
  • 12

1 Answers1

1

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?.

Community
  • 1
  • 1
Werner Henze
  • 16,404
  • 12
  • 44
  • 69
  • This is the solution .It works as I add a explicitly instantiate after the definition at cpp file, but in this way my slice_vec() function can only work for integer type, which weakens the advantage of using template. There is a better solution:http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file . It is a convention to define the template function right at the header file. – Zhang Mar 16 '17 at 02:03