Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 << "
";
    std::cout << y.foo << "
";
    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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...