template <typename T> classbeta { private: template <typename V> // 模板类作为成员 classhold { private: V val; public: hold(V v = 0) : val(v) {} voidshow()const{ cout << val << endl; } V Value()const{ return val; } }; hold<T> q; // 成员模板的对象 hold<int> n; // 成员模板的对象 public: beta( T t, int i) : q(t), n(i) {} // 构造函数这样传递信息 template<typename U> // 函数模板作为成员 U blab(U u, T t){ return (n.Value() + q.Value()) * u / t; } voidShow()const{ q.show(); n.show();} };
intmain() { beta<double> guy(3.5, 3); cout << "T was set to double\n"; guy.Show(); cout << "V was set to T, which is double, then V was set to int\n"; cout << guy.blab(10, 2.3) << endl; cout << "U was set to int\n"; cout << guy.blab(10.0, 2.3) << endl; cout << "U was set to double\n"; cout << "Done\n"; // std::cin.get(); return0; }
template <template <classType,intMAX>classThing> // template <class Type,int MAX> class 类型的参数 Thing classCrab { private: Thing<int,5> s1; Thing<double,5> s2; public: Crab() {}; // assumes the thing class has push() and pop() members boolpush(int a, double x){ return s1.push(a) && s2.push(x); } boolpop(int & a, double & x){ return s1.pop(a) && s2.pop(x); } };
intmain() { Crab<Stack> nebula; // Stack must match template <typename T> class thing int ni; double nb; cout << "Enter int double pairs, such as 4 3.5 (0 0 to end):\n"; while (cin>> ni >> nb && ni > 0 && nb > 0) { if (!nebula.push(ni, nb)) break; }
while (nebula.pop(ni, nb)) cout << ni << ", " << nb << endl; cout << "Done.\n"; return0; }