共享库中的模板 class 仅适用于隐式和显式实例化

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

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

--- 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> > 无效?对于不工作的,我得到 'undefined reference' 错误。代码非常简化,而且简化得如此之多的代码不会发生这种情况,但是很难将代码分解到不再工作的程度,因为它嵌入在一个相当复杂的项目中。我主要是在这里寻找可能导致此问题的提示。

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