问题描述
背景:
我目前在视觉工作室中构建了一个游戏引擎项目,这样我的引擎被编译成一个dll,用于另一个项目游戏消费。这个想法是我可以交换不同的游戏项目,仍然使用相同的引擎dll代码。在我的引擎代码中,我创建了自己的框架,所有其他引擎代码将使用它。这将有助于将我的实现与我的其余代码分开,并且如果需要,可以使修改更容易。
I currently have a game engine project structured in visual studio so that my 'Engine' is compiled into a dll for another project 'Game' to consume. The idea being I can swap out different game projects and still use the same engine dll code. Within my engine code I'm creating my own framework for which all other engine code will use. This will help to separate my implementation from the rest of my code and make modification easier if need be.
由于我所有的框架代码都在dll本身内使用,而不是在游戏中,我以为我可以实现模板。但是,我随时尝试使用Engine框架实现模板,仍然会收到未定义的符号错误。
Since all my framework code with be used within the dll itself and not within 'Game' I thought I could implement templates. However, I still receive the 'undefined symbol' error anytime I try and implement templates with the Engine framework.
问题:
有没有办法解决链接器中模板的未定义符号错误在我的dll内,而不必我的模板将消耗的每个类型(例如类模板MyClass< int>
,类模板MyClass< float>
等)?如果没有,有什么建议可以实现我的引擎和不同的游戏项目,以保持灵活的不同的方式?感谢任何投入。
Is there a way to get around the 'undefined symbol' errors for templates from the linker within my dll without having to explicitly define every type my template will consume (ex. class template MyClass<int>
, class template MyClass<float>
, etc.)? If not, are there any suggestions on different ways I could implement my engine and different game projects to still keep things flexible? Thanks for any input.
我不想明确定义模板类可以使用的所有类型,因为如果我想创建说我自己的矢量模板类(因为我必须定义一个不同的类),那将会变得相当大。
P.S. I don't want to have to explicitly define all types a templated class could use since that would get rather large if I wanted to create say my own vector template class (as I would have to define A LOT of different classes).
推荐答案
模板intantiations在编译时生成,所以如果你不想单独声明所有可能的实例,那么您必须移动所有模板定义才能包含在头文件中。
Template intantiations are generated at compile time, so if you don't want to individually declare all possible instantiations then you must move all template definitions to be included with the header file.
这样做的一个常见方法是每个类都有所有的模板定义在一个内联文件中,例如一个 .inl
或 .cxx
文件,然后将该内联文件包含在相应的头文件。
One common way of doing this is for each class to have all of the template definitions in an inline file e.g a .inl
or .cxx
file, and then to include that inline file at the end of the corresponding header file.
例如,对于具有单个模板函数的类 Foo
:
For example, for a class Foo
with a single templated function:
Foo.hpp
的内容:
class Foo
{
template <typename T>
void bar();
};
#include "Foo.inl" // Include template definitions
内容的 Foo.inl
:
template <typename T>
void Foo::bar()
{
// body
}
这样,每当 Foo :: bar< T>
与新的 T
那么将会生成一个新的模板实例化。
That way, whenever Foo::bar<T>
is used with a new T
then an a new template instantiation will be generated.
这篇关于四处逛逛问题在C ++中的Dll模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!