运行代码:
#include"std_lib_facilities.h"
template <class T>struct S
{
private:
T val;
public:
S<T>() :val(T()) {}
S<T>(T tt) : val(tt) {};
T& get();
void set(T tt) { val = tt; }
ostream& operator << (ostream& oss);
};
template<class T> ostream& operator <<(ostream& oss, vector<T>& vv)
{
for (int i = 0; i < vv.size(); i++)
oss << vv[i] << " ";
return oss;
}
template<class T> ostream& S<T>::operator <<(ostream& oss)
{
return oss << val;
}
template<class T> T& S<T>::get()
{
return val;
}
int main()
try
{
S<int>s_int;
cout << s_int.get()<<"\n";
s_int.set(34);
cout << s_int.get() << "\n";
S<char>s_char('d');
cout << s_char.get()<<"\n";
S<double>s_double(3.3);
cout << s_double.get()<<"\n";
S<string>s_string("the_first_time");
cout << s_string.get()<<"\n";
vector<int>v_int;
v_int.push_back(32);
v_int.push_back(44);
S<vector<int>>s_vector_int(v_int);
cout << s_vector_int.get()<<"\n";
return 0;
}
catch (exception& e) {
cerr << "error:" << e.what() << '\n';
keep_window_open();
return 1;
}
catch (...) {
cerr << "Oops:unknown exception!\n";
keep_window_open();
return 2;
}
运行结果: