What's the difference betwwen explicit instantiaion and explicit specialization?

A

Andy

Hi,

I got a little confused on 'instantiation' and 'specialization',
espcially for explicit instantiation and explicit sepcialization. Can
anybody explain the difference?

Thanks a lot!

Andy
 
A

Alf P. Steinbach

* Andy:
I got a little confused on 'instantiation' and 'specialization',
espcially for explicit instantiation and explicit sepcialization. Can
anybody explain the difference?

You specialize a template when you provide a definition for some actual
template parameter, e.g., saying "in general, use the general definition,
but for template parameter T=int, use this more specialized definition".

This specialized definition may or may not be actually used, so
specialization by itself does not cause a more thorough analyzis than
the original template definition.

You instantiate a template when you cause the compiler to generate code for
the template. This requires all template parameters given actual parameters,
and it causes full-blown analysis of this specialization of the template.
For example, you declare an object of the template type, or you call a
templated function. At that point the template definition is expanded to
actual, ordinary C++ code (the template instance), which is subject to the
usual C++ compilation (OK, some rules, e.g. about multiple definitions, are
slightly different). You can also instantiate a template without using it, via
special syntax.
 
S

Shezan Baig

Andy said:
Hi,

I got a little confused on 'instantiation' and 'specialization',
espcially for explicit instantiation and explicit sepcialization. Can
anybody explain the difference?

Thanks a lot!

Andy

If I have a templated class:

template <typename FOO> class Bar { ... };

I explicitly *instantiate* Bar<char> like this:

template <> class Bar<char>;

Notice that the implementation of Bar<char> does not change (i.e., it
is not specialised).

When I *specialise* Bar<char>, I do this:

template <> class Bar<char> { ... };

Now, Bar<char> has a new meaning (i.e., the template class 'Bar' now
does something "special" when used with 'char' as the template
argument).

Hope this helps,
-shez-
 
M

Max M.

Shezan said:
I explicitly *instantiate* Bar<char> like this:

template <> class Bar<char>;

The correct syntax for explicit instantiation is

template class Bar<char>;

(with no '<>'.)


MM
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top