【发布时间】:2011-06-09 15:43:29
【问题描述】:
我已经阅读了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 的回答后简化这个问题
【问题讨论】:
-
不管重载决议如何,在单独的 .cpp 文件中定义模板是没有用的。调用者必须看到 i lt 才能实例化。
-
@n.m.,如果所有定义都去头文件,如果这个头文件也被另一个文件包含,会导致多定义的链接错误。
-
@ls 如果你内联它就不会
-
@ls 模板是一个(臭名昭著的)例外。
-
@AJG85 +1 用于内联解决方案:-)
标签: c++ templates template-specialization