I'm doing this example that involves two generic functions, one that takes a vector of type T and another that takes an array of type T. The functions worked when I put both the declaration and definition within main, but when I split them up between the header file and implementation I get an undefined reference to the functions when I call them from main.
Code://main.cpp #include <cstdlib> #include <iostream> #include <vector> #include "headers.h" using std::vector; using std::cout; using std::endl; int main() { int a_grades[8] = {87, 95, 100, 83, 75, 49, 56, 94}; vector<int> v_grades(a_grades, a_grades + 9); cout << median(a_grades) << endl; cout << median(v_grades) << endl; //49 56 75 83 87 94 95 100 system("PAUSE"); return EXIT_SUCCESS; }Code://headers.h #ifndef headers_h #define headers_h #include <vector> template <class T> double median(std::vector<T> vec); template <class T> double median(T vec); #endiferrorsCode://headers.cpp #include <iostream> #include <vector> #include <stdexcept> #include <cstddef> #include "headers.h" using std::vector; template <class T> double median(vector<T> vec) { typedef typename vector<T>::size_type vec_sz; vec_sz size = vec.size(); if (size == 0) throw std::domain_error("median of an empty vector"); std::sort(vec.begin(), vec.end()); vec_sz mid = size/2; return size % 2 == 0 ? (vec[mid] + vec[mid-1]) / 2 : vec[mid]; } template <class T> double median(T vec) { size_t size = sizeof(vec)/sizeof(*vec); if (size == 0) throw std::domain_error("median of an empty vector"); std::sort(vec, vec + size); size_t mid = size/2; return size % 2 == 0 ? (vec[mid] + vec[mid-1]) / 2 : vec[mid]; }
Code:In function `main': [Linker error] undefined reference to `double median<int*>(int*)' [Linker error] undefined reference to `double median<int>(std::vector<int, std::allocator<int> >)' ld returned 1 exit status [Build Error] [practice.exe] Error 1



LinkBack URL
About LinkBacks



Want to add some