I am trying to learn about templates, I want my class pair to be able to hold two objects of any type. I just want to provide an accessor function for obj1 now. But I get the following error when I try to complile:

error: expected initializer before '<' token T1 pair<T1,T2>::getObj1() 

My code is:

#include <iostream> #include <stdio.h> #include <string.h> using namespace std; template <class T1, class T2> class pair { public: pair(const T1& t1, const T2& t2) : obj1(t1), obj2(t2){}; T1 getObj1(); private: T1 obj1; T2 obj2; }; template <class T1, class T2> T1 pair<T1,T2>::getObj1() { return obj1; } int main() { return 0; } 
8

1 Answer

pair is name of a standard class and with the using namespace std, there is a collision.

Several solutions :

  • Rename your class to something else.
  • Dont use the using statement
2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.