0

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?

ramgorur
  • 2,104
  • 4
  • 26
  • 39
  • 1
    You should simply put the implementation into the header file. Template is like macro, and it will not initiate the template in cpp file. – Scott Deng Dec 22 '15 at 22:49
  • 1
    BTW `_TEST_H_` is **undefined behavior**! Do NOT use an identifier that starts with underscore then upper case letter or an identifier with two underscores in a row. – Czipperz Dec 22 '15 at 22:56
  • @Czipperz could you please elaborate a little bit more? why a single underscore is undefined but a double is not? – ramgorur Dec 23 '15 at 00:19
  • @ramgorur The following are undefined: `_Hi`, `hi__h`, `__x`. Even `_x` is undefined in the _global namespace_ (so macros count!). The following are well defined: `_hi`, `hi_i_h`, `hi_h`. http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier#228797 – Czipperz Dec 23 '15 at 01:47

0 Answers0