C++ partial specialization of function templates 和 partial ordering of function template 的区别

partial specialization of function templates 和 partial ordering of function template 的区别

概念辨析

区别

  • partial specialization of function templates 指函数模板偏特化,即显式地指定函数模板的部分模板参数而非全部参数;
  • partial ordering of function template 也是一种函数模板偏特化,但指的是模板参数范围上的偏特化。实际调用中,当有多个偏特化的函数模板匹配时,编译器会按照偏特化的精确程度(范围)进行排序,选择调用最精确的(范围最小的)版本

总结

函数模板偏特化(partial specialization of function templates)包括模板参数个数的偏特化和模板参数范围的偏特化,而 partial ordering of function template 指的就是模板参数范围的偏特化中,编译器所作的按照不同偏特化版本的匹配程度进行排序选择的动作

举例

partial ordering of function template

#include <iostream>

using namespace std;

template <class T>
void func(T) {
	cout << "func<T> is called!" << endl;
}

template <class T>
void func(T*) {
	cout << "func<T*> is called!" << endl;
}

template <class T>
void func(const T*) {
	cout << "func<const T*> is called!" << endl; 
}

int main () {
	int i = 0;
	int* p = &i;
	const int* cp = &i;
	func(i);	// func<T> is called!
	func(p);	// func<T*> is called!
	func(cp);	// func<const T*> is called! 
	return 0;
}

partial specialization of function templates

除了上面这一种范围上的偏特化以外,最常见的是以下的参数个数的偏特化:

#include <iostream>

using namespace std;

template <class T>
void func(T) {
	cout << "func<T> is called!" << endl;
}

template <>
void func<int>(int) {
	cout << "func<int> is called!" << endl;
}

template <>
void func<char>(char) {
	cout << "func<char> is called!" << endl; 
}

int main () {
	int i = 0;
	char ch = 'a';
	func("");	// func<T> is called!
	func(i);	// func<int> is called!
	func(ch);	// func<char> is called!
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Air浩瀚

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值