如何强制 C++ 模板的特定实例进行实例化?

How do I force a particular instance of a C++ template to instantiate?(如何强制 C++ 模板的特定实例进行实例化?)

本文介绍了如何强制 C++ 模板的特定实例进行实例化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

见标题.我有一个模板.我想强制实例化模板的特定实例.我该怎么做?

See title. I have a template. I want to force a particular instance of a template to instantiate. How do I do this?

更具体地说,您能否强制实例化抽象模板类?

More specifically, can you force an abstract template class to instantiate?

我可能会详细说明,因为我有同样的问题.在我的例子中,我正在构建一个库,一些模板实现很大并且包含很多东西,但只为几种类型生成.我想在库中编译它们并导出所有方法,但不要在任何地方都包含带有代码的头.

I might elaborate as I have the same question. In my case I am building a library, some of the template implementations are large and include lots of stuff, but are only generated for a couple of types. I want to compile them in the library and export all the methods, but not include the header with the code everywhere.

即:

template<class T>
OS_EXPORT_DECL class MyTmpl
{
    T *item1;
public:
    inline T *simpleGetT() { return(item1); } /* small inline code in here */ } 
    T *doSomeReallyBigMergeStuff(T *b); // note only declaration here
};

// *** implementation source file only seen inside library

template<class T>
MyTmpl<T>::doSomeReallyBigMergeStuff(T *b)
{
    ... a really big method, but don't want to duplicate it, 
        so it is a template ...
}

我当然可以引用库中的所有方法,这将强制它们编译和导出,但我不想将不需要的代码添加到库中,例如项目的参数格式和调用它们的代码等

I could of course reference all the methods inside the library which would force them to compile and export but the desire isn't to add un-needed code to the library like the argument formatting for the items and the code to call them etc.

?????具体来说,我正在为多个版本的 MSC 和 GCC 以及英特尔编译器构建库.

????? specifically I am building the library for several versions of MSC and GCC and intel compilers.

推荐答案

不能强制实例化泛型模板,编译器只能在类型完全已知的情况下生成代码.

You can't force generic templates to instantiate, the compiler can only generate code if the type is completely known.

通过显式提供所有类型来强制实例化:

Forcing an instantiation is done by providing all types explicitly:

template class std::vector<int>;

Comeaus 模板常见问题 详细介绍了相关问题.

Comeaus template FAQ covers the related issues in some detail.

这篇关于如何强制 C++ 模板的特定实例进行实例化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何强制 C++ 模板的特定实例进行实例化?

基础教程推荐