c++ - C++ 中多个基本模板的模板特化

标签 c++ templates template-specialization

我有两个模板函数:

template<class X> void foo(X a)
{
    cout << "Template 1" << endl;
}


template<class X> void foo(X *a)
{
    cout << "Template 2" << endl;
}

现在,如果我定义一个特化,例如:

template<> void foo<>(int *a)
{
    cout << "Specialization 1" << endl;
}

此特化属于模板 1 还是模板 2。另外,如果我在模板 2 之前或之后定义特化,这有关系吗?

最佳答案

X 替换为 int 并查看哪个主模板产生匹配的签名:

template<class X> void foo(X a)

成为

template <> void foo<int>(int)

template<class X> void foo(X *a)

成为

template<> void foo<int>(int *)

所以,只能是第二个函数的特化。由于函数不特化第一个重载,因此有必要在定义特化之前声明第二个主模板,因为特化无法特化第一个主模板。

如果在特化中没有明确指定模板参数,则根据 14.8.2.6 [temp.deduct.decl] 第 1 段使用正常参数推导规则找到相关的主模板:

In a declaration whose declarator-id refers to a specialization of a function template, template argument deduction is performed to identify the specialization to which the declaration refers. Specifically, this is done for explicit instantiations (14.7.2), explicit specializations (14.7.3), and certain friend declarations (14.5.4).

此参数推导考虑了主模板的部分排序,即它找到了第二个主模板。我没有陷入阅读打油诗之前的段落的陷阱,但警告是真实的:如果更改第二个主要模板和特化的顺序,我认为你会遇到麻烦!小心提到的自焚警告。

关于c++ - C++ 中多个基本模板的模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18283851/

相关文章:

c++ - 具有潜在共享对象的循环转换

c++ - 全局指针变量如何存储在内存中?

c++ - 如何从另一个类获取std::bitset的大小?

c++ - 单函数的类部分模板特化,如何解决其他成员的未定义错误

c++ - 所有子类的模板特化

c++ - 可变参数模板模板参数可以部分特化吗?

c++ - 这个 pow() 函数在 while 循环 C++ 中发生了什么?

c++ - 定义概念时是否允许 OR (`||` )?

c++输出流不适用于模板和 namespace

c++ - 在 C++ 中传递模板化对象?