共享库中的模板类仅使用隐式和显式实例化

Template class in shared library only working with implicit AND explicit instantiation

本文关键字:实例化 共享      更新时间:2023-10-16

我有两个类在一个共享库中。

--- foo.h
template <class T>
class Foo
{
Foo();
void doSomething(void);
...
};
--- foo.cpp
#include "foo.h"
#include "bar.h"
template <class T>
Foo:Foo()
{
};
template <class T>
void Foo::doSomething(void)
{
};
// Here I put the explicit/implicit instantiations (see below)
--- bar.h
template <class T>
class Bar
{
...
};
--- bar.cpp
template <class T>
class Bar
{
...
};
template class Bar<int>;

还有一个主函数,它使用这些:

#include "foo.h"
#include "bar.h"
int main(void)
{
Foo<Bar<int> > foobar; // Or Foo<int> foobar; for version 5
foobar.doSomething();
}

现在,为了完成这项工作,我想实例化Foo。我尝试了 5 种方法:

版本 1:显式实例化(不起作用(

template class Foo<Bar<int> >;

版本 2:隐式实例化光(不起作用(

void dummy(void){Foo<Bar<int> > foobar;}

版本 3:隐式实例化(不起作用(

void dummy(void){Foo<Bar<int> > foobar; foobar.doSomething();}

版本4:隐式和显式实例化(有效(

template class Foo<Bar<int> >;
void dummy(void){Foo<Bar<int> > foobar; foobar.doSomething();}

版本 5:使用非模板化类型显式实例化(有效(

template class Foo<int>; // Works, if you change the main as well

为什么只有版本 4 适用于Foo<Bar<int> >?为什么Foo<int>有效,Foo<Bar<int> >不起作用?对于不起作用的,我收到"未定义的引用"错误。代码非常简化,并且不会发生在简化的代码中,但是很难将代码分解到不再起作用的程度,因为它嵌入在一个相当复杂的项目中。我主要是在这里寻找可能导致这种情况的提示。

好的,我能够弄清楚。问题是编译顺序。Bar<int>被显式实例化,但显然这发生在显式实例化Foo<Bar<int> >之后,这以某种方式阻止了它被实例化。在同一模块中template class Foo<Bar<int> >;之前添加另一个template class Bar<int>;解决了该问题。