What is compile-time polymorphism and why does it only apply to functions?

ihtkwot picture ihtkwot · Dec 10, 2009 · Viewed 24.2k times · Source

What is compile-time polymorphism and why does it only apply to functions?

Answer

Jerry Coffin picture Jerry Coffin · Dec 10, 2009

Way back when, "compile time polymorphism" meant function overloading. It applies only to functions because they're all you can overload.

In current C++, templates change that. Neil Butterworth has already given one example. Another uses template specialization. For example:

#include <iostream>
#include <string>

template <class T>
struct my_template { 
    T foo;
    my_template() : foo(T()) {}
};

template <>
struct my_template<int> {
    enum { foo = 42 };
};

int main() { 
    my_template<int> x;
    my_template<long> y;
    my_template<std::string> z;
    std::cout << x.foo << "\n";
    std::cout << y.foo << "\n";
    std::cout << "\"" << z.foo << "\"";
    return 0;
}

This should yield 42, 0, and "" (an empty string) -- we're getting a struct that acts differently for each type.

Here we have "compile time polymorphism" of classes instead of functions. I suppose if you wanted to argue the point, you could claim that this is at least partially the result of the constructor (a function) in at least one case, but the specialized version of my_template doesn't even have a constructor.

Edit: As to why this is polymorphism. I put "compile time polymorphism" in quotes for a reason -- it's somewhat different from normal polymorphism. Nonetheless, we're getting an effect similar to what we'd expect from overloading functions:

int value(int x) { return 0; }
long value(long x) { return 42; }

std::cout << value(1);
std::cout << value(1L);

Function overloading and specialization are giving similar effects. I agree that it's open to some question whether "polymorphism" applies to either, but I think it applies about equally well to one as the other.