C++ Visual C+中的外部模板是否存在错误+;?
鉴于此代码:C++ Visual C+中的外部模板是否存在错误+;?,c++,visual-c++,c++11,visual-studio-2012,C++,Visual C++,C++11,Visual Studio 2012,鉴于此代码: //header.h template <class T> class Foo { public: Foo(T t) : t(t) {} T t; }; //source1.cpp: #include "header.h" extern template class Foo<int>; int main() { Foo<int> f(42); } 但是,如果我链接到source2.cpp,它会工作(正如我预期的那样): #包括“h
//header.h
template <class T>
class Foo
{
public:
Foo(T t) : t(t) {}
T t;
};
//source1.cpp:
#include "header.h"
extern template class Foo<int>;
int main()
{
Foo<int> f(42);
}
但是,如果我链接到source2.cpp,它会工作(正如我预期的那样):
#包括“header.h”
模板类Foo;
根据这篇博文,extern模板应该从VC10开始就得到支持。
另一方面,是否有办法在Windows/Visual Studio上列出对象文件中的名称?在Linux上,我会:
$ nm source1.o
U _ZN3FooIiEC1Ei <- "U" means that this symbol is undefined.
0000000000000000 T main
$nm source1.o
U_ZN3FooIiEC1EiC++11 14.7.2/10“显式实例化”表示:
除了内联函数和类模板专门化,
显式实例化声明具有抑制
它们引用的实体的隐式实例化
类模板Foo
中的构造函数是内联的。如果您按照如下方式构造标头,VS2012将以您期望的方式工作:
//header.h
template <class T>
class Foo
{
public:
Foo(T t);
T t;
};
template <class T>
Foo<T>::Foo(T t) : t(t)
{
}
使用内联的ctor编译示例:
00A 00000000 SECT4 notype () External | ??0?$Foo@H@@QAE@H@Z (public: __thiscall Foo<int>::Foo<int>(int))
^^^^^
00A 00000000第4节notype()外部|?0$Foo@H@@QAE@H@Z(public:_thiscall Foo::Foo(int))
^^^^^
啊,内联,我没想到。这就解释了。
//header.h
template <class T>
class Foo
{
public:
Foo(T t);
T t;
};
template <class T>
Foo<T>::Foo(T t) : t(t)
{
}
dumpbin /symbols test.obj
...
008 00000000 UNDEF notype () External | ??0?$Foo@H@@QAE@H@Z (public: __thiscall Foo<int>::Foo<int>(int))
^^^^^
...
00A 00000000 SECT4 notype () External | ??0?$Foo@H@@QAE@H@Z (public: __thiscall Foo<int>::Foo<int>(int))
^^^^^