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.
To instantiate a template class explicitly, follow the template keyword by a declaration (not definition) for the class, with the class identifier followed by the template arguments. template class Array<char>; template class String<19>; When you explicitly instantiate a class, all of its members are also instantiated.
cpp, there are two instantiations: template class B<int> and B<float>.
The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation to handle a specific set of template arguments is called a specialization.
In order for any code to appear, a template must be instantiated: the template arguments must be provided so that the compiler can generate an actual class (or function, from a function template).
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.
What you also can try is explicit instantiation:
template class vector<int>; // class
template int& vector<int>::operator[](int); // member
template int convert<int,double>(double); // function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With