65,184
社区成员




template <class T>
T function(T , T);
struct sa;
template <> sa& function<sa&>(sa& , sa& );
template <class T>
T& function(T& , T&);
struct sa;
template <> sa& function<sa>(sa& , sa& );
// CPP_t.cpp : コンソール アプリケーションのエントリ ポイントを定義します。
//
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
template <class T>
T function(T , T);
struct sa
{
string s;
int value;
};
template <> sa& function<sa&>(sa& , sa& ); //??????????
int _tmain(int argc, _TCHAR* argv[])
{
sa x, y;
x.s = "X";
x.value = 3;
y.s = "Y";
y.s = 98;
//cout << function(10, 15) << endl; //模版并非如此“万能”
cout << function(x, y).s << endl; //不会出错了
cin.get();
return 0;
}
template <class T>
T function(const T a,const T b)
{
return (a.value>b.value?a:b); //改成这样,如果不想改,那就必须保证<class T>的类型都重载了">"符。
}
template <> sa& function<sa&>(sa& a, sa& b) //这个是干什么的?万一还有个struct as岂不是又要为as写一个“模版”函数?
{
return (a.value>b.value?a:b);
}
// CPP_t.cpp : コンソール アプリケーションのエントリ ポイントを定義します。
//
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
template <class T>
T function(T , T);
struct sa
{
string s;
int value;
};
template <> sa& function<sa&>(sa& , sa& );
int _tmain(int argc, _TCHAR* argv[])
{
sa x, y;
x.s = "X";
x.value = 3;
y.s = "Y";
y.s = 98;
cout << function(10, 15) << endl;
cout << function(x, y).s << endl;
cin.get();
return 0;
}
template <class T>
T function(T a, T b)
{
return (a>b?a:b);
}
template <> sa& function<sa&>(sa& a, sa& b)
{
return (a.value>b.value?a:b);
}
#include <iostream>
#include <string>
using namespace std;
template <class T>
T function(T , T);
struct sa
{
string s;
int value;
int operator > (const sa &b)
{
if(value > b.value)
return 1;
else
return 0;
}
};
template <class T>
T function(T a, T b)
{
return a > b? a:b;
}
template <> sa& function<sa&>(sa& , sa& );
int main(int argc, char* argv[])
{
sa x, y;
x.s = "X";
x.value = 3;
y.s = "Y";
y.value = 98;
cout << function(10, 15) << endl;
cout << function(x, y).s << endl;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
template <class T>
T const& function(T const&, T const&);
struct sa
{
string s;
int value;
};
template <>
sa const& function(sa const& , sa const& ); //模板特化
int main()
{
sa x, y;
x.s = "X";
x.value = 3;
y.s = "Y";
y.s = 98;
cout << function(10, 15) << endl;
cout << function<sa>(x, y).s << endl;
cout << function<sa>(x, y).s << endl; //这里可以显式的指定类型;
return 0;
}
template <class T>
T const& function(T const& a, T const& b)
{
return (a>b ? a:b);
}
template<>
sa const& function(sa const& a, sa const& b)
{
return (a.value>b.value?a:b);
}