dinsdag 26 juni 2007

Explicit Specializations (Templates)

Suppose you define a structure like the following:

struct job
{
char name[40];
double salary;
int floor;
};

Also, suppose you want to be able to swap the contents of the two structures. The original template, the one before this blog, uses the following code to effect a swap:

temp = a;
a = b;
b = temp;

Because C++ allows you to assign one structure to another, this works fine, even if type Any is a
job structure. But suppose you want only to swap the salary and floor members, keeping the name members unchanged. This requires different code, but the arguments to Swap() would be the same as for the first case (references to two job structures), so you can't use template overloading to supply alternative code.

However, you can supply a specialized function definition, called an explicit specialization, with the required code, If the compiler finds a specialized definition that exactly matches a function call, it uses that definition without looking for templates.

The specialization mechanism has changed with the evolution of C++. We'll look at the current form as mandated by the C++ Standard.

- For a given function name, you can have a non-template function, a template function, and an explicit specialization template function, along with overloaded versions of all of these.

- The prototype and definition for an explicit specialization should be preceded by template <> and should mention the specialized type by name.

- A specialization overrides the regular template, and a non-template function overides both.

Here's how prototypes for swapping type job structures would look for these three forms:

// non-template function prototype
void Swap(job &, job &);

// template prototype
template
void Swap(Any &, Any &);

// explicit specialization for the job type
template <> void Swap(job &, job &);

As mentioned previously, if more than one of these prototypes is present, the compiler chooses the non-template version over explicit specializations and template versions, and it chooses an explicit specialization over a version generated from a template. For example, in the following code, the first call to Swap() uses the general template, and the second call uses the explicit specialization, based on the job type:

...
template // template
void Swap(Any &, Any &);

// explicit specialization for the job type
template <> void Swap(job &, job &);
int main()
{
double u, v;
...
Swap(u, v); // use template
job a, b;
...
Swap(a, b); // use void Swap(job &, job &)
}

The in Swap is optional because the function argument types indicate that this is a specialization for job. Thus the prototype can also be written this way:

template <> void Swap(job &, job &); // simpler form

Geen opmerkingen: