我正在学习使用Linux上的gcc 4.8.1
选项-frepo
详细了解C++模板实例化。我的理解是,这个选项会对模板实例化进行一些清理操作,使得即使在多个翻译单元中隐式实例化相同的模板,每个实例也只会在链接的二进制文件中出现一次。如果需要特定的上下文,请参考以下示例文件:
// file: template.h
template <typename T>
class Box {
public:
void func (const T & t) {} // member function
template <T t>
T func_tmpl () { return t; } // member function template
template <T t>
class inner { // inner class template
public:
const static T value = t;
};
};
并且
// file: main.cpp
#include "template.h"
int main (int argc, char * argv[]) {
Box<int> b;
b.func(3); // member function invocation
int x = b.func_tmpl<7>(); // member function temple instantiation
Box<int>::inner<5> g; // inner class template instantiation
int y = g.value;
return 0;
}
当我编译 (g++ -frepo -c main.cpp
) 并检查符号 (nm -C main.o
),我发现:
0000000000000000 T main
U Box<int>::func(int const&)
U int Box<int>::func_tmpl<7>()
正如您所预期的那样,func
和func_tmpl
被列为未定义的符号。我不确定的是为什么inner
没有被列出来;它在类模板中定义,本身是一个类模板,并在main.cpp
中实例化。有人能提供inner
未包含在main.o
符号中的原因吗?无论是否定义都可以。
nm
不显示类,它显示函数和全局变量。它将显示Box<int>::inner<5>::value
,但在这里它是“未使用的”。 - Marc GlisseBox<int>::inner<5>::value
实际上是全局变量吗?我认为它的范围更为狭窄,因为需要使用::
来标识它。再次感谢! - Eric Paniagua