c++ - 函数模板特化和 Abrahams/Dimov 示例

标签 c++ template-specialization function-templates

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

假设标题中有一些 3rd 方代码,您无法修改:

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)

问题是:

如果我按原样得到上面的声明,是否有可能我现在可以针对 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;
}

关于c++ - 函数模板特化和 Abrahams/Dimov 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14786008/

相关文章:

C++14 函数式 logical_not 函数

c++ - WinAPI 定时互斥锁

c++ - 枚举类型的 Notype 模板的特化 - 错误 : template argument is invalid

c++ - 如何理解T&和T const&的偏序规则

c++ - 编译模板函数时形式参数列表不匹配

c++ - LLVM 字符串值对象 : How can I retrieve the String from a Value?

c++ - 是否可以将 SDL2 与智能指针一起使用?

c++ - 析构函数的部分特化

c++ - 嵌套模板类中的 std::conditional

没有参数的 C++ 可变参数函数