如何强制实例化C ++模板的特定实例? [英] How do I force a particular instance of a C++ template to instantiate?

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

问题描述

查看标题。我有一个模板。我想强制模板的特定实例实例化。




$



b
$ b

我可能会详细说明,因为我有同样的问题。在我的情况下,我正在建立一个库,一些模板实现是大的,包括大量的东西,但只生成几种类型。我想在库中编译它们,并导出所有的方法,但不要在任何地方包含代码的头。



ie:

 模板< class T> 
OS_EXPORT_DECL class MyTmpl
{
T * item1;
public:
inline T * simpleGetT(){return(item1); } / *这里的小内联代码* /}
T * doSomeReallyBigMergeStuff(T * b); // note only declaration here
};

// ***实现源文件仅在库中可见

模板< class T>
MyTmpl< T> :: doSomeReallyBigMergeStuff(T * b)
{
...一个很大的方法,但不想复制它,
因此它是一个模板...
}



我当然可以引用库中的所有方法将迫使它们编译和导出,但是希望不是像库的参数格式化和调用它们的代码那样向库添加不需要的代码。



具体来说,我正在为MSC和GCC和intel编译器的几个版本构建库。

解决方案



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

 模板类std :: vector< int> ;;  export>模板常见问题详细介绍了相关问题。


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.

ie:

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.

????? 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 template FAQ covers the related issues in some detail.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆