I am trying to overload <<
operator so that I can use it cout
. I do not have any class, the code is divided into test.h/test.cpp
and main.cpp
files --
first test.h
:
#ifndef _TEST_H_
#define _TEST_H_
#include <ostream>
#include <vector>
using std::ostream ; using std::vector ;
template <typename T>
ostream& operator<< (ostream &os, const vector<T> &vec);
#endif
now test.cpp
:
#include <vector>
#include <iostream>
#include "test.h"
using std::ostream ; using std::cout ; using std::endl ;
using std::vector ;
template <typename T>
ostream& operator<< (ostream &os, const vector<T> &vec) {
if(vec.size() > 0) {
os << "[ " << vec[0] << ", " ;
for(int i = 1 ; i < vec.size()-1 ; i++) os << vec[i] << ", ";
os << vec[vec.size()-1] << " ]" ;
}
else
os << "" ;
return os ;
}
the main.cpp
looks like this --
#include <vector>
#include <string>
#include <iostream>
#include "test.h"
using std::cout ; using std::endl ;
using std::vector ; using std::string ; using std::to_string ;
int main()
{
vector<string> vec ;
for(int i = 0 ; i < 10 ; i++)
vec.push_back(to_string(i));
cout << vec << endl ; // printing the vector here
return 0;
}
and I am compiling the code like --
g++ -g -Wall -std=c++11 *.cpp -I. -o test
the code is extremely straight forward, nothing complicated, but I am getting this linker error --
/tmp/ccczf9Rq.o: In function `main':
/tmp/mdp/main.cpp:18: undefined reference to `std::ostream& operator<< <std::string>(std::ostream&, std::vector<std::string, std::allocator<std::string> > const&)'
collect2: error: ld returned 1 exit status
what is going on?