c++ 模板函数学习

模板函数的好处和作用

模板在各种项目中,可以避免功能相似函数的重复定义,可以少做一些重复性的工作

类模板

比如如下一个类,为了两两比较Dog,Snake和Human三类,我们可能需要写6个函数。因为项目中并不一定一次实现所有功能,所以有时这些功能的实现是缓慢而不易察觉得消耗精力和时间。

但使用模板类中定义函数 则只需要定义一次则可以一直复用

template 
struct AnimalCompare {
public:
	AnimalCompare() {};
	std::string  getMaxFootCountAnimal(T a, G b) {
		if (a.footCount > b.footCount)
			return a.name;
		return b.name;
	};
	std::string getMaxLengthAnimal(T a, G b) {
		if (a.length > b.length)
			return a.name;
		return b.name;
	};
	std::string getMaxIQAnimal(T a, G b) {
		if (a.IQ > b.IQ)
			return a.name;
		return b.name;
	};

};
struct Dog {
	std::string name = "dog";
	double length = 2;
	int footCount = 4;
	int IQ = 70;
};
struct Snake {
	std::string name = "snake";
	double length = 10;
	int footCount = 0;
	int IQ = 50;
};
struct  Human {
	std::string name = "human";
	double length = 1.7;
	int footCount = 2;
	int IQ = 150;
};

int main() {
	Dog dog;
	Snake snake;
	Human human;
	AnimalCompare util1;
	AnimalCompare util2;
	AnimalCompare util3;
	std::cout<

c++ 模板函数学习_第1张图片

但是模板函数不能推导出返回值类型 所以这么写是会报错的

template 
struct AnimalCompare {
public:
	AnimalCompare() {};
	template
	M  getMaxFootCountAnimal(T &a, G &b) {
		if (a.footCount > b.footCount)
			return a;
		return b;
	};
	template
	N getMaxLengthAnimal(T &a, G &b) {
		if (a.length > b.length)
			return a;
		return b;
	};
};

函数模板

延续刚才简单的例子,这里模板函数也可以非常简洁完成需求函数得定义

struct Dog {
	std::string name = "dog";
	int IQ;
	int id;
	Dog(int id, int IQ) :id(id), IQ(IQ) {}
};
struct Snake {
	std::string name = "snake";
	int IQ;
	int id;
	Snake(int id, int IQ) :id(id), IQ(IQ) {}
};
typedef struct  Human {
	std::string name = "human";
	int IQ;
	int id;
	Human(int id, int IQ) :id(id), IQ(IQ) {}
}*pHuman;
template
void printMinAgeAnimalName(T t) {
	auto it = std::min_element(t.begin(), t.end(), [&](G g1, G g2) {return g1.IQ > g2.IQ;});
	std::cout << it->id << "\n";
}
int main() {
	std::vector dogVec = {};
	std::vector snakeVec = {};
	std::vector humanVec = {};
	dogVec.push_back(Dog(0, 10));
	dogVec.push_back(Dog(1, 20));
	snakeVec.push_back(Snake(2, 15));
	snakeVec.push_back(Snake(3, 35));
	humanVec.push_back(Human(4, 11));
	humanVec.push_back(Human(5, 17));
	printMinAgeAnimalName,Dog>(dogVec);
	printMinAgeAnimalName, Snake>(snakeVec);
	printMinAgeAnimalName, Human>(humanVec);
}

c++ 模板函数学习_第2张图片

值得注意一点是 在一开始可以直接指定模板函数得类,但是T还是会根据传入类重新定义

struct Dog {
	std::string name = "dog";
	double length = 2;
	int footCount = 4;
	int IQ = 70;
};
struct Snake {
	std::string name = "snake";
	double length = 10;
	int footCount = 0;
	int IQ = 50;
};
struct  Human {
	std::string name = "human";
	double length = 1.7;
	int footCount = 2;
	int IQ = 150;
};
template
void printMinAgeAnimalName(T t) {
	std::cout << t.name << "\n";
}
int main() {
	Dog dog;
	Snake snake;
	Human human;
	printMinAgeAnimalName(human);

}

在这里插入图片描述

参考

https://blog.csdn.net/zjy900507/article/details/79626547

你可能感兴趣的:(c++,fitsCore)