How to use overloaded operators with template types?
-
Hello, I use a template class where I would like to overload the operator [ ]. My intention is that not only the instances of the class will call the operator but also the types of the instances. I have tried the following code. It works but never the operator [] is called. Please could tell me if is there a solution to use my own overloaded operator with any type like int, float, long etc.. Thanks for your kind answers. //ClassTest.h template class ClassTest { public: ClassTest(){}; virtual ~ClassTest(){}; type* Date; inline type& operator[](UINT i_index){return (at(i_index));}; }; main() { // test 1 ClassTest theInt; theInt.Date = new int[10]; theInt.Date[0] =5; //Does not call type& operator[] //test2 int array[] = {1996,1997,1998} ClassTest figure; figure.Date = array; int xx = figure.Date[1]; //Does not call type& operator[] }
-
Hello, I use a template class where I would like to overload the operator [ ]. My intention is that not only the instances of the class will call the operator but also the types of the instances. I have tried the following code. It works but never the operator [] is called. Please could tell me if is there a solution to use my own overloaded operator with any type like int, float, long etc.. Thanks for your kind answers. //ClassTest.h template class ClassTest { public: ClassTest(){}; virtual ~ClassTest(){}; type* Date; inline type& operator[](UINT i_index){return (at(i_index));}; }; main() { // test 1 ClassTest theInt; theInt.Date = new int[10]; theInt.Date[0] =5; //Does not call type& operator[] //test2 int array[] = {1996,1997,1998} ClassTest figure; figure.Date = array; int xx = figure.Date[1]; //Does not call type& operator[] }
You haven't called the [] operator for the template class in either of your examples. Instead of theInt.Date[0] =5; // This is using default [] operator to index into the "Date" member. it should be theInt[0] = 5; This will call your operator but it won't compile since you have no "at()" method defined. Mark
"Posting a VB.NET question in the C++ forum will end in tears." Chris Maunder