C++模板特化

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/i_chaoren/article/details/80458269

【理论待补充...】

下面是一个函数模板特化的例子;

///  模版特化
template <class T>
int compare(const T left, const T right)
{
	std::cout << "in template<class T>..." << std::endl;
	if (left < right) return -1;
	if (left > right) return 1;
	return 0;
}

//  这个是一个特化的函数模版
template < >
int compare(const char* left, const char* right)
{
	std::cout << "in special template< >..." << std::endl;
	return strcmp(left, right);
}

//  特化的函数模版, 两个特化的模版本质相同, 因此编译器会报错
// error: redefinition of 'int compare(T, T) [with T = const char*]'|
//template < >
//int compare<const char*>(const char* left, const char* right)
//{
//	std::cout << "in special template< >..." << std::endl;
//
//	return strcmp(left, right);
//}

int main()
{
	cout << compare(1, 4) << endl;

	const char *left = "bello";
	const char *right = "aorld";
	cout << compare(left, right) << endl;

	return 0;
}


参考:https://blog.csdn.net/gatieme/article/details/50953564

猜你喜欢

转载自blog.csdn.net/i_chaoren/article/details/80458269