// test1_template.cc basic test of templates #include #include // this is definately NOT !! using namespace std; template class foo; // a declaration that foo is a template class template // declaration or specification of foo class foo // the user gets to choose a type for 'T' { public: foo(); void put(T value); T get(int &j); private: int mine(T &a_value); T a; int i; }; // remember the ending semicolon template // implementation or body of foo foo::foo() { i = 1; // can not initialize 'a' here because we do not know what type 'T' is } template void foo:: put(T value) { a = value; // since 'a' and 'value' are both type 'T' this is OK } template T foo::get(int &j) { j = ++i; // 'j' was passed by reference and gets incremented 'i' return a; // return 'a' whatever type it is } int main(int argc, char *argv[]) { foo x; // in object 'x', the type 'T' is double double y; int j; x.put(1.5); // put the value 1.5 into 'a' in 'x' y = x.get(j); // increment 'i' in 'x' and return 'a' cout << "j= " << j << " y= " << y << endl; foo glob; // in object 'glob' , the type 'T' is string::string string y_string; glob.put("abc"); // put the string "abc" int 'a' in 'glob' y_string = glob.get(j); // increment 'i' in 'glob' and return 'a' cout << "j= " << j << " y_string= " << y_string << endl; return 0; }