Alex Rivera | Logout

What are some other languages that support "partial specialization"?

Asked 2008-12-18T07:27:26.587
12

Partial template specialization is one of the most important concepts for generic programming in C++. For example: to implement a generic swap function:

template <typename T>
void swap(T &x, T &y) {
  const T tmp = x;
  y = x;
  x = tmp;
}

To specialize it for a vector to support O(1) swap:

template <typename T, class Alloc>
void swap(vector<T, Alloc> &x, vector<T, Alloc> &y) { x.swap(y); }

So you can always get optimal performance when you call swap(x, y) in a generic function;

Much appreciated, if you can post the equivalent (or the canonical example of partial specialization of the language if the language doesn't support the swap concept) in alternative languages.

EDIT: so it looks like many people who answered/commented really don't known what partial specialization is, and that the generic swap example seems to get in the way of understanding by some people. A more general example would be:

template <typename T>
void foo(T x) { generic_foo(x); }

A partial specialization would be:

template <typename T>
void foo(vector<T> x) { partially_specialized_algo_for_vector(x); }

A complete specialization would be:

void foo(vector<bool> bitmap) { special_algo_for_bitmap(bitmap); }

Why this is important? because you can call foo(anything) in a generic function:

template <typename T>
void bar(T x) {
  // stuff...
  foo(x);
  // more stuff...
}

and get the most appropriate implementation at compile time. This is one way for C++ to achieve abstraction w/ minimal performance penalty.

Hope it helps clearing up the concept of "partial specialization". In a way, this is how C++ do type pattern matching without needing the explicit pattern matching syntax (say the matc

Edit
Report

2 Answers

0

Actually, you can (not quite; see below) do it in C# with extension methods:

public Count (this IEnumerable<T> seq) {
    int n = 0;
    foreach (T t in seq)
        n++;
    return n;
}

public Count (this T[] arr) {
    return arr.Length;
}

Then calling array.Count() will use the specialised version. "Not quite" is because the resolution depends on the static type of array, not on the run-time type. I.e. this will use the more general version:

IEnumerable<int> array = SomethingThatReturnsAnArray();
return array.Count();
answered 2008-12-19T08:54:15.020
-3

Java has generics, which allow you to do similar sorts of things.

answered 2008-12-19T04:01:20.150

Your Answer