函数模板专业化和Abrahams/Dimov示例

Function template specialization and the Abrahams/Dimov example

本文关键字:Dimov 示例 Abrahams 专业化 函数模板      更新时间:2023-10-16

(我假设知道这个问题中的Abrahams/Dimov示例。)

假设在一个类似这样的头中有一些第三方代码,您不能修改:

template<class T> void f(T);    // (1) base template 1
template<class T> void f(T *);  // (2) base template 2
template<> void f<>(int *);     // (3) specialization of (2)

问题是:

如果我已经按原样得到了上面的声明,我现在是否有可能将基础模板1专门用于T = int *(例如)的情况?

或者仅仅是对基础模板2的声明就意味着基础模板1不能再专门化了(至少对于指针来说)?

您可以通过在函数名称后的尖括号中显式指定模板参数来重载(1)(参见C++11 Standard 14.7.3)

#include <iostream>
using namespace std;
template<class T> void f(T)    // (1) base template 1
{
    cout << "template<class T> void f(T)" << endl;
}
template<class T> void f(T *)  // (2) base template 2
{
    cout << "template<class T> void f(T *)" << endl;
}
//template<> void f<>(int *);     // (3) specialization of (2)
template<> void f<int*>(int *)     // (4) specialization of (1)
{
    cout << "f<int*>(int *)" << endl;
}

int main() {
    int i;
    f(&i); // calls (2) since only base-templates take part in overload resolution
    return 0;
}

你可以试着然后来找我们。但我不明白为什么它不起作用。如果是T = int*,它将按您的意愿工作。因此,no2将是int* * 的参数