yuefengz
yuefengz

Reputation: 3358

C++ template partial explicit instantiation

Can we partially instantiate a C++ template explicitly?

template class <typename T, int N>
class MyClass {
  ...
};

template<int N> class MyClass<int, N>;  // not meant for specification
template<int N> class MyClass<float, N>;

just like we can have:

template class <typename T>
class MyClass {
  ...
};

template class MyClass<int>;
template class MyClass<float>;

Upvotes: 4

Views: 1963

Answers (1)

Richard Hodges
Richard Hodges

Reputation: 69882

A template is not a class. It's a template. (A blueprint to build a class). It can only become a class when all template parameters are accounted for.

having written this (typo corrected):

template <typename T, int N>
class MyClass {

};

You may by all means do this:

template<int N> class MyClass<int, N>;  
template<int N> class MyClass<float, N>;

But it is not instantiating a template (because that has no meaning), nor is it instantiating a concrete class formed from that template. What it is actually doing is forward-declaring the existence of a partially specialised (possibly infinite) subset of the the template.

You may also do this:

template<int N> class MyClass<int, N> {};  
template<int N> class MyClass<float, N> {};

Which has partially specialised MyClass for <int, [all values of N]> and <float, [all values of N]>.

However, this template subset is still not instantiated. Merely defined.

to actually instantiate a template, whether partially specialised or not, we must name it, accounting for all template arguments.

Upvotes: 6

Related Questions