简体   繁体   English

模板声明顺序在c ++中是否重要

[英]Does template declaration order matter in c++

The following code is taken from http://www.gotw.ca/publications/mill17.htm 以下代码摘自http://www.gotw.ca/publications/mill17.htm

#include<iostream>
using namespace std; 

template<class T> // (a) a base template 
void f( T ){
  cout << "base1\n";   
}

template<class T> // (b) a second base template, overloads (a) 
void f( T* ){
  cout << "base2\n";   
}

template<>        // (c) explicit specialization of (b) 
void f(int*){
  cout << "base3\n";   
}

int main()
{
  int *p = NULL; 
  f( p ); 
}

The output in the above case is "base3". 上述情况下的输出是“base3”。 But if I write (c) above (b), the output is "base2". 但如果我在(b)上面写(c),则输出为“base2”。 I tested the above code at cpp.sh. 我在cpp.sh上测试了上面的代码。 Can anyone please tell me the reason? 谁能告诉我原因?

Yes, the order matters here. 是的,订单在这里很重要。 If you move (c) before (b), then it becomes an explicit specialization of (a) instead of (b). 如果你在(b)之前移动(c),那么它变成(a)而不是(b)的显式特化。

In overload resolution between the two primary templates, ie (a) and (b), (b) is always selected; 在两个主要模板之间的重载分辨率中,即(a)和(b),总是选择(b); but (c) is not the specialization of (b) again and then won't be invoked, so you'll get the output "base2". 但是(c)不再是(b)的特化,然后不会被调用,所以你得到输出“base2”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM