c++模板小例子

  1. 需要注意的是,模板中函数或方法,要在类或头文件中实现。
  2. 关键字typename 和class基本等同。
  3. 构造类模板时,要指明模板参数类型,而函数模板则不用指明参数类型。

#pragma once


#include 

#include 

using namespace std;

template <typename T>
T compare(T  t1, T  t2) {
	if (t1 > t2) {
		return t1;
	}
	else {
		return t2;
	}
};

template <typename T>
class TEST {

public:
	T m_t;

	TEST() {};

	virtual ~TEST() {};

	T compare(T  t1, T  t2) {
		return t1 > t2;
	};
	int comparestr(T  t1 =  string, T  t2 =  string) {

		string s1 = t1;
		string s2 = t2;
		char * buf1 = (char*)s1.c_str();
		char * buf2 = (char*)s2.c_str();
		return (buf1[0]> buf2[0]);
	};
};







#include 

#include 
#include 
#include "main.h"

using namespace std;

int main() {

	try {
		double resd = 0;
		int res = 0;
		const char * resc = 0;
		resd = compare(7.01, 7.1);
		res = compare(6, 5);

		resc = compare("hello", "world");

		TEST<char*> test;

		TEST<double> testd;

		int result = 0;

		double resultd = testd.compare(6.6789, 7.01);

		resultd = testd.compare(6.6789, 6.7);

		result = test.comparestr("testo","hello");

		throw("hello world!\r\n");	
	}
	catch (char * ex) {
		try {
			printf("throw string:%s\r\n", ex);

			throw(12345678);
		}
		catch (int e) {
			printf("throw number:%d\r\n", e);
			//exit(0);
		}
	}

	return 0;

}

你可能感兴趣的:(开发语言,c++,开发语言)