我已经阅读了Why Not Specialize Function Templates,经过一些实验,我发现了一件有趣的事情。这是main.cxx:
// main.cxx
#include <iostream>
// Declarations
/*
template<class T>
void foo(T);
template<>
void foo(int*);
template<class T>
void foo(T*);
*/
// Definition and specification
template<class T>
void foo(T x)
{
std::cout << "T version." << std::endl;
}
template<>
void foo(int *i)
{
std::cout << "int* version." << std::endl;
}
template<class T>
void foo(T *x)
{
std::cout << "T* version" << std::endl;
}
int main(int argc, char** argv)
{
int *p;
foo(p);
}
有趣的是:如果我保留声明部分的注释,则行为就像文章所说的那样,即如果 int* 版本的定义在其定义之前,则将使用 T* 版本,反之亦然。但是,如果取消注释声明块,无论我在定义或声明中使用哪种顺序,都只会调用 int* 版本。我的问题是这个声明是如何影响决议的?
有任何想法吗?我在 x86_64-redhat-linux 上使用 g++ 4.2.2
编辑:在看到 AProgrammer 的回答后简化这个问题