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;
}