Manish Karir submitted an interesting problem. The following code would not compile.
#include <iostream> using namespace std; template<class T> class Vec { private: T* arryptr; int size; int capacity; public: Vec(void){}; Vec(int cap){}; Vec(int cap,T init){}; Vec(Vec<T> const& v){}; ~Vec(void){}; void add(T a){}; T& operator[](int n){return arryptr[n];}; Vec<T>& operator=(Vec<T> const& rhs){}; bool operator==(Vec<T> const& rhs){}; bool operator!=(Vec<T> const& rhs){}; friend ostream & operator<<(ostream & out,Vec<T> &v); int getsize(void) {return size;}; int getcapacity(void){}; }; template <class T> ostream& operator<<(ostream& out, Vec<T>& v) { for (int i=0;i < v.getsize(); i++) { out << v[i] << " "; } out << endl; return out; } void main(){ Vec<float> v1(1); v1.add(34.34); v1.add(23.343); cout << v1 << endl; }
Solution:
Change the friend prototype to -
friend ostream & operator<< <T>(ostream & out,Vec<T> &v);
Where the friend is now explicitly templated. Compilation is achieved.
An interesting side note: The original program compiled in MSVC++ but not g++. g++ is correct with respect to the standard in that templating must be explicitly defined. There may be some strict compiling flag in MS that I did not have on, but I am not sure.