什么是编译时多态性,为什么它只适用于函数?
什么是编译时多态性,为什么它只适用于函数?
What is compile-time polymorphism and why does it only apply to functions?
推荐答案
回到过去,编译时多态性"意味着函数重载.它仅适用于函数,因为它们都是你可以重载的.
Way back when, "compile time polymorphism" meant function overloading. It applies only to functions because they're all you can overload.
在当前的 C++ 中,模板改变了这一点.Neil Butterworth 已经举了一个例子.另一个使用模板专业化.例如:
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;
}
这应该产生 42
、0
和 ""
(一个空字符串)――我们得到一个行为不同的结构每种类型.
This should yield 42
, 0
, and ""
(an empty string) -- we're getting a struct that acts differently for each type.
这里我们有类而不是函数的编译时多态性".我想如果你想争论这一点,你可以声称这至少部分是构造函数(一个函数)在至少一种情况下的结果,但 my_template
的特殊版本没有甚至有一个构造函数.
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.
至于为什么这是多态性.我将编译时多态性"放在引号中是有原因的――它与普通的多态性有些不同.尽管如此,我们得到的效果类似于我们期望从重载函数中获得的效果:
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.
相关文章