本文介绍了在另一个标题中强制模板实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模板化的集合"类.我不需要在每个源文件中重新编译代码.但是,此集合应与未在模板类的定义中定义的DataTypes(class SpecialDataMember : DataMember)一起使用.这就是为什么我不能在模板源文件中强制实例化(通过将定义移至源文件并添加template LinkCollection<DataMember>;)的原因,因为模板的定义必须可以在其他源文件("SpecialDataMember.cpp")中访问).

I have a templated "collection" class. I don't wan't the code be recompiled in every source file. But this collection should be used with DataTypes (class SpecialDataMember : DataMember) not defined on definition of the the template class.This is why I can't force the instantiation in the template source file (throug moving the definitions to the source file and add template LinkCollection<DataMember>;), because the definitions of the template must be accessible in other source files ("SpecialDataMember.cpp").

是否可以使"SpecialDataMember.o"保留LinkCollection<SpecialDataMember>的代码.每个SpecialDataMember.h的包含者都应该知道我将LinkCollection<SpecialDataMember>留给了链接器.

Is it possible to make "SpecialDataMember.o" hold the code for LinkCollection<SpecialDataMember>. Every includer of SpecialDataMember.h should know I leave LinkCollection<SpecialDataMember> to the linker.

我看到两个选项,但我不知道它们是否有效:

I see two options but I don't know if they work:

  1. 制作两个模板标头(带有标头保护),一个标头不带定义.

SpecialDataMember.h

SpecialDataMember.h

// ..
include "LinkCollection.h"
// ..

SpecialDataMember.cpp

SpecialDataMember.cpp

// ..
include "LinkCollectionImpl.h"
// ..
include "SpecialDataMember.h"
// ..
template LinkCollection<SpecialDataMember>;

所有"SpecialDataMember.h"的包含者都不知道模板的定义,因此他们将让链接器执行其工作.链接器将在SpecialDataMember.o中找到LinkCollection<SpecialDataMember>的实例化.那是对的吗?但是我必须维护两个头文件.有没有更好的方法来获得这种效果?

All includers of "SpecialDataMember.h" will not know the definitions of the template so they will let the linker do his work.And the linker will find the instantiation of LinkCollection<SpecialDataMember> in SpecialDataMember.o. Is that correct?But I would have to maintain two header Files. Is there a better way to gain this effect?

  1. 使用模板派生类

如果我在"SpecialDataMember"头文件和源文件中创建一个特殊的class SpecialDataMemberLinkCollection : LinkCollection<SpecialDataMemberLink>,我可以改为引用该特殊类,因此编译器知道该类和基类模板都有实例化,并保留了对链接器起作用.会按预期工作吗?

If I create a special class SpecialDataMemberLinkCollection : LinkCollection<SpecialDataMemberLink> in the "SpecialDataMember" header and source file, I could reference this special class instead and so the compiler knows there is an instantiation of that class and the base class template and leaves the work to the linker. Will this work as expect?

推荐答案

简单,只需输入:

extern template class LinkCollection<SpecialDataMember>;

标头中的

,指示编译器不要实例化该模板并将其留给另一个文件.

in the header, which tells the compiler not to instantiate that template and leave it to another file.

然后在一个SpecialDataMember.cpp文件中提供该实例化:

Then in one SpecialDataMember.cpp file provide that instantiation:

template class LinkCollection<SpecialDataMember>;

这篇关于在另一个标题中强制模板实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 17:58