c++ - 如何确定将使用哪个模板

标签 c++ templates

我正在学习 C++ 中的模板,我发现了以下示例。

据我所知,如果没有匹配的非模板函数,编译器应该总是尝试使用最“专业”的模板,但在这个例子中,第一次调用导致调用函数 a(T*) 而不是一个(整数*)。为什么?为什么第二次调用的行为不同?

template<typename T>
void a(T) {cout << "(T)" << endl;}

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

template<typename T>
void a(T*) {cout << "(T*)" << endl;}

template<typename T>
void b(T) {cout << "(T)" << endl;}

template<typename T>
void b(T*) {cout << "(T*)" << endl;}

template<>
void b<>(int*) {cout << "(int)" << endl;}

int main()
{
  int i;
  a(&i);
  b(&i); 
  return 0;
}

The resulting output is:

(T*)
(int)

我希望它是:

(int)
(int)

最佳答案

仅考虑主模板(因此没有特化)来选择更特化的重载。

一旦使用主模板完成选择,我们将使用特化(如果有的话)。

现在,template<> void a<>(int*);只能是template<typename T> void a(T)的特化(其他版本没看过)。

template<> void b<>(int*);template<typename T> void b(T*)的特化(它是更专业的匹配重载)。

请注意,您可以选择 b 的特化通过提供模板而不是让编译器推断:

  • template<> void b<>(int*) -> template<typename T> void b(T*) with T=int
  • template<> void b<int>(int*) -> template<typename T> void b(T*) with T=int
  • template<> void b<int*>(int*) -> template<typename T> void b(T) with T=int*

因此:

int i;
a(&i); // a<T*> with T=int*, no specialization for a<U*> (U=int) exist -> generic template called
b(&i); // b<T*> with T=int*, specialization for b<U*> (U=int) exists -> specialization called

关于c++ - 如何确定将使用哪个模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56473597/

相关文章:

c++ - fork时产生的错误

c++ - 使用模板化基础编译时间类选择器

C++ 泛型类设计,其方法返回子类

c++ - 调用与方法同名的函数

c++ - Const 限定符和前向引用

c++ - 指向 vector 的指针

c++ - 连续计算器程序的段错误

C++构造函数返回嵌入式系统

templates - 将CIB文件连接/链接到 Cappuccino 中的常规应用程序模板

C++ 模板 : cannot find base class type parameter method when overloaded