Tim
Tim

Reputation: 5681

C++ template function: explicit instantiate one or more specializations

Is it possible to explicit instantiate one or more specializations of a template function? Second, does it matter if the function is a class member? Is it legal C++11 and also is it accepted by compilers so it doesn't come with problems?

Upvotes: 0

Views: 656

Answers (1)

dyp
dyp

Reputation: 39111

Is it possible to explicit instantiate one or more specializations of a template function?

Yes, however, [temp.explicit]/5:

For a given set of template arguments, if an explicit instantiation of a template appears after a declaration of an explicit specialization for that template, the explicit instantiation has no effect.


Second, does it matter if the function is a class member?

No, AFAIK; [temp.explicit]/1:

A class, a function or member template specialization can be explicitly instantiated from its template. A member function, member class or static data member of a class template can be explicitly instantiated from the member definition associated with its class template. An explicit instantiation of a function template or member function of a class template shall not use the inline or constexpr specifiers.

Example from [temp.explicit]/3:

template<class T> class Array { void mf(); };
template class Array<char>;

template void Array<int>::mf();

template<class T> void sort(Array<T>& v) { /∗ ... ∗/ }
template void sort(Array<char>&);    // argument is deduced here

namespace N {
template<class T> void f(T&) { }
}
template void N::f<int>(int&);

Is it legal C++11 and also is it accepted by compilers so it doesn't come with problems?

Well, yes, but for libraries there's always the problem of ABI compatibility; especially if different compilers have been used for library and library user (e.g. program including that library). The C++ Standard does not specify an ABI.

Upvotes: 1

Related Questions