函数模板编程时间:2021-09-03 16:36:48Common.h #ifndef _COMMON_H_ #define _COMMON_H_ /* 函数模板 全部采用包含编译模型 */ /* 函数模板声明 */ template<typename T> int Compare(const T& v1, const T& v2); template<typename T> int Compare0(T v1, T v2); template<typename T, typename U> T Compare1(U v1, U v2); template<typename T, typename U, typename X> T Compare2(U v1, X v2); template<typename T> int Compare3(const T& v1, const T& v2); template<> int Compare0<const char*>(const char* v1, const char* v2); /* 模板特化 放在头文件,避免重复定义 */ template<> int Compare0<const char*>(const char* v1, const char* v2) { int nRet = 0; nRet = strcmp(v1, v2); return nRet; } #include "Common.cpp" #endif Common.cpp #include <string.h> template<typename T> int Compare(const T& v1, const T& v2) { int nRet = 0; if (v1 > v2) { nRet = 1; } else if(v1 < v2) { nRet = -1; } return nRet; } template<typename T> int Compare0(T v1, T v2) { int nRet = 0; if (v1 > v2) { nRet = 1; } else if(v1 < v2) { nRet = -1; } return nRet; } template<typename T, typename U> T Compare1(U v1, U v2) { T nRet = 0; if (v1 > v2) { nRet = 1; } else if(v1 < v2) { nRet = -1; } return nRet; } template<typename T, typename U, typename X> T Compare2(U v1, X v2) { T nRet = 0; return nRet; } template<typename T> int Compare3(const T& v1, const T& v2) { int nRet = 0; if (v1 > v2) { nRet = 1; } else if(v1 < v2) { nRet = -1; } return nRet; } stdafx.cpp // stdafx.cpp : source file that includes just the standard includes // TemplateStudy.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file stdafx.h // stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once #ifndef _WIN32_WINNT // Allow use of features specific to Windows XP or later. #define _WIN32_WINNT 0x0501 // Change this to the appropriate value to target other versions of Windows. #endif #include <stdio.h> #include <tchar.h> // TODO: reference additional headers your program requires here TemplateStudy.cpp // TemplateStudy.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> using namespace std; #include "Common.h" int _tmain(int argc, _TCHAR* argv[]) { cout << Compare(10, 12) << endl; /* 多个类型形参的实参必须完全匹配 一般而言,不会转换实参以匹配已有的实例化,而是会产生新的实例 例外:编译器允许两种转换 1.const转换 2.数组或函数到指针的转换 */ /* cout << Compare(10.2, 12) << endl; error */ int nV1 = 10; const int nV2 = 32; cout << Compare0(nV1, nV2) << endl; //const convert int a[10]; int b[42]; cout << Compare0(a, b) << endl; //calls Compare0(int*, int*) /* 调用显示指定模板实参 */ int c = 12; int d = 14; cout << Compare1<int>(c, d) << endl; Compare2<int, double, int>(10.1, 11); Compare2<int, int>(10, 23); /* 调用特化的模板函数 */ const char* v1 = "1234"; const char* v2 = "12345"; cout << Compare0(v1, v2) << endl; return 0; }