Unit1.cpp
#include <vcl.h>
#include "2-1 函数模板示例.cpp"
#pragma hdrstop
#include "Unit1.h"
// ---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
// ---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) {
}
// ---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender) {
int a = 5, b = 3;
float x = 1.3, y = 2.8;
char m = 'A', n = 'B';
Memo1->Clear();
Memo1->Lines->Add(Max(a, b)); // 完整写法Max<int>(a,b)
Memo1->Lines->Add(Max(x, y)); // 完整写法Max<float>(x,y)
Memo1->Lines->Add(Max(m, n)); // 完整写法Max<char>(m,n)
}
// ---------------------------------------------------------------------------
2-1 函数模板示例.cpp
#include <iostream>
template <class T>
T Max(T a, T b)
{
if (a > b)
return a;
return b;
}
输出效果