Template class question.


R. Clayton (rclayton@monmouth.edu)
(no date)


I have a template class

  template <typename T1, typename T2>
  struct myclass {
    T1 xcord;
    T2 ycord;
    myclass(T1 x, T2 y) : xcord(x), ycord(y) { }
    };

Is this o.k.?

  int main() {
    myclass<int, int> me(10, 5);
    }

Can I use the same type for both template parameters?

  Your class is essentially the same as the std::pair class. As the fifth
  programming assignment amply demonstrated, std::pair works fine when both
  template parameters represent the same type, so your class should too.

  To be on the safe side, let's compile it and see:

    $ cat t.cc
    template <typename T1, typename T2>
    struct myclass {
      T1 xcord;
      T2 ycord;
      myclass(T1 x, T2 y) : xcord(x), ycord(y) { }
      };

    int main() {
      myclass<int, int> me(10, 5);
      }

    $ g++ -c -ansi -pedantic -Wall t.cc
    t.cc: In function `int main()':
    t.cc:9: warning: unused variable `myclass<int, int> me'

    $

  On the other hand, you could also argue that myclass should only use one
  template parameter, because both coordinates should have the same type. As it
  stands, myclass<vector<int>, string> is a legal instantiation of myclass,
  although it may not make much sense as an (x, y) coordinate pair. (Of course,
  myclass<vector<int> > may not make much sense either, but at least it's
  consistent with the idea of having a single type for both coordinates.)



This archive was generated by hypermail 2.0b3 on Fri May 10 2002 - 12:45:04 EDT