0

I've created a class that's designed to rotate a vector. (I realize this functionality basically already exists in STL, I'm just trying get a handle on template classes.)

My specification file:

template <class T>
class ShiftVec {
private:
    vector<T> vec;

public:
    ShiftVec(vector<T>);
    vector<T> getVec();
    void shiftRight(int);
    void shiftLeft(int);
};

My implementation file:

template <class T>
ShiftVec<T>::ShiftVec(vector<T> v) {
    vec = v;
}

template <class T>
vector<T> ShiftVec<T>::getVec() {
    return vec;
}

template <class T>
void ShiftVec<T>::shiftRight(int n) {
    rotate(vec.begin(),
           vec.end()-n, // this will be the new first element

template class ShiftVec<int>;
template class ShiftVec<double>;
template class ShiftVec<bool>;
template class ShiftVec<string>;

When I run this, I get a bunch of errors that look like this:

Undefined symbols for architecture x86_64:
  "ShiftVec<int>::shiftRight(int)", referenced from:
      _main in main.o
  "ShiftVec<int>::getVec()", referenced from:
      _main in main.o
  "ShiftVec<int>::ShiftVec(std::__1::vector<int, std::__1::allocator<int> >)", referenced from:
      _main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I'm not sure exactly what's going wrong here. A push in the right direction would be helpful.

123
  • 8,733
  • 14
  • 57
  • 99

1 Answers1

0

You should declare each of the templated functions WITH the type as well in the implementation file.

For example: For your implementation:

template <class T>
ShiftVec<T>::ShiftVec(vector<T> v) {
    vec = v;
}

You should add a line under the implementation like so:

template <class T>
ShiftVec<T>::ShiftVec(vector<T> v) {
    vec = v;
}
template ShiftVec<int>::ShiftVec(vector<int> v); // <<< this is the line added

The final line above is key here.

shafeen
  • 2,431
  • 18
  • 23
  • I've added several versions(types) of the `ShiftVec()` class, but I'm getting a `Thread 1: BAD_EXC_ACCESS` error now. (I edited my question with the changes) – 123 Feb 23 '16 at 18:58