共享库中的模板类仅与隐式AND显式实例化一起使用

时间:2017-06-30 18:27:04

标签: c++ templates shared-libraries instantiation

我在共享库中有两个类。

upstream tomcat {
    server 127.0.0.1:8080 fail_timeout=0;
}
server {
        listen 80 default_server;
        listen [::]:80 default_server;
        server_name mydomain;
        return 301 https://$server_name$request_uri;
}
server {
    # SSL configuration
    listen 443 ssl http2 default_server;
    listen [::]:443 ssl http2 default_server;
    include snippets/ssl-mydomain.conf;
    include snippets/ssl-params.conf;`
.
.
.`

使用它们的主要功能:

--- 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>;

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

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

#include "foo.h"
#include "bar.h"

int main(void)
{
    Foo<Bar<int> > foobar; // Or Foo<int> foobar; for version 5
    foobar.doSomething();
}

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

template class Foo<Bar<int> >;

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

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

版本4:隐式AND显式实例化(工作)

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

版本5:使用非模板化类型(作品)的显式实例化

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

为什么只有版本4适用于template class Foo<int>; // Works, if you change the main as well ?为什么Foo<Bar<int> >有效,但Foo<int>没有?对于不起作用的人,我得到了未定义的参考文献&#39;错误。代码非常简单,并且代码很简单,但是很难将代码分解到它不再工作的地步,因为它已经嵌入了在一个相当复杂的项目中。我主要在寻找可能导致此问题的提示。

1 个答案:

答案 0 :(得分:0)

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