Summary
This article describes the various polymorphism in C + +. This paper focuses on the dynamic polymorphism of object-oriented and static polymorphism based on template, and probes into the combination of two technologies.
Keywords
Multi-State inherited virtual function template macro function overload generic programming generic mode
Introduction
The term polymorphic (polymorphism) originally originated in the Greek polumorphos, meaning in a variety of forms or patterns of the situation. In the field of programming, a widely recognized definition is "an ability to associate different special behaviors with a single generalization mark." Unlike a purely object-oriented programming language, polymorphism in C + + has a broader meaning. In addition to the common dynamic polymorphism (dynamical polymorphism) that takes effect through class inheritance and virtual function mechanisms in the runtime, templates also allow different special behaviors to be associated with a single generalization notation, which is referred to as static polymorphism because it is processed at compile time rather than runtime. Polymorphism).
In fact, macro and function overloading mechanisms with variables also allow different special behaviors to be associated with a single generalization token. However, the behavior that we are accustomed not to show them is called polymorphism (or static polymorphism). Today, when we talk about polymorphism, if we don't explicitly refer to it, the default is dynamic polymorphism, while static polymorphism refers to a template based polymorphism. However, in this article on the subject of various polymorphic technologies in C + +, we first review another "polymorphism" that has long been debated in the C + + community: Functional polymorphism (function polymorphism) and, more often, "macro polymorphism (Macro polymorphism)".
function polymorphism
Which is what we often say about function overloads (functions overloading). Based on a different argument list, the same function name can point to a different function definition:
// overload_poly.cpp
#include <iostream>
#include <string>
// 定义两个重载函数
int my_add(int a, int b)
{
return a + b;
}
int my_add(int a, std::string b)
{
return a + atoi(b.c_str());
}
int main()
{
int i = my_add(1, 2); // 两个整数相加
int s = my_add(1, "2"); // 一个整数和一个字符串相加
std::cout << "i = " << i << "\n";
std::cout << "s = " << s << "\n";
}
Depending on the argument list (type, number, or both), My_add (1, 2) and My_add (1, "2") are compiled separately for calls to My_add (int, int) and my_add (int, std::string). The principle of implementation is that the compiler names the functions of the same name based on different argument lists, and these functions become different functions of the same name. For example, perhaps a compiler will reorganize the My_add () function names into My_add_int_int () and My_add_int_str () respectively.