問題描述
見標題.我有一個模板.我想強制實例化模板的特定實例.我該怎么做?
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?
我可能會詳細說明,因為我有同樣的問題.在我的例子中,我正在構(gòu)建一個庫,一些模板實現(xiàn)很大并且包含很多東西,但只為幾種類型生成.我想在庫中編譯它們并導(dǎo)出所有方法,但不要在任何地方都包含帶有代碼的頭.
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 ...
}
我當然可以引用庫中的所有方法,這將強制它們編譯和導(dǎo)出,但我不想將不需要的代碼添加到庫中,例如項目的參數(shù)格式和調(diào)用它們的代碼等
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 以及英特爾編譯器構(gòu)建庫.
????? 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 模板常見問題 詳細介紹了相關(guān)問題.
Comeaus template FAQ covers the related issues in some detail.
這篇關(guān)于如何強制 C++ 模板的特定實例進行實例化?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!