5

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
    try removing semicolon after the constructor. Dec 4, 2013 at 13:42
  • No that doesnt fix it, thanks though! Dec 4, 2013 at 13:43
  • You are clashing with std::pair, try something like mypair instead. Dec 4, 2013 at 13:43
  • 1
    it is not duplicate, it is more generic question about partial specializations in same namespace Jan 24, 2016 at 13:02
  • 1
    @Sergei is right. I managed to get this error without involving using namespace std. The question would benefit from an answer that actually addresses what the error means in general, not just pointing out that a totally different question (there is no similarity of the titles) has a solution that fits to this particular example.
    – bluenote10
    Jan 14, 2019 at 16:32

1 Answer 1

16

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
  • Came here to say the exact same thing.
    – Joe Z
    Dec 4, 2013 at 13:45
  • 6
    +1. Yes, this is why it's bad to use using namespace std; (among other reasons, of course) Dec 4, 2013 at 13:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.