共享库中的模板类仅使用隐式和显式实例化
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> >
不起作用?对于不起作用的,我收到"未定义的引用"错误。代码非常简化,并且不会发生在简化的代码中,但是很难将代码分解到不再起作用的程度,因为它嵌入在一个相当复杂的项目中。我主要是在这里寻找可能导致这种情况的提示。
好的,我能够弄清楚。问题是编译顺序。Bar<int>
被显式实例化,但显然这发生在显式实例化Foo<Bar<int> >
之后,这以某种方式阻止了它被实例化。在同一模块中template class Foo<Bar<int> >;
之前添加另一个template class Bar<int>;
解决了该问题。
相关文章:
- 从C++实例化QML
- 设计一个只能由特定类实例化的类(如果可能的话,通过make_unique)
- 如何创建一个空的全局类并在启动时实例化它
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 约束和显式模板实例化
- 为什么包含windows.h会产生语法错误,从而阻止类的实例化?(C2146,C2065)
- 对象实例化调用构造函数的次数太多
- 如何使用非默认构造函数实例化模板化类
- 静态数据成员模板专用化的实例化点在哪里
- 错误的cv::face FacemarkLBF实例化
- C++的解析器在可以区分比较和模板实例化之前会做什么?
- 如何从共享库中移植导出模板实例化
- 为共享指针C++单独实例化对象
- 为什么在共享库中仅导出其中一些C++模板实例化?
- 共享库中的模板类仅使用隐式和显式实例化
- 模板类静态在最终二进制文件中跨共享库以不同方式实例化是否一致
- 共享库:具有部分模板专用化和显式模板实例化的未定义引用
- 在泛型lambda表达式的所有实例化之间共享的局部静态变量
- 只有当类重写方法时,在动态加载的共享库中实例化的类才会丢失XCode 4.3/4.4 typeinfo
- 类模板的所有实例化是否可以共享相同的模板独立成员函数