Мультиметод
Мультиме́тод (англ. multimethod) или мно́жественная диспетчериза́ция (англ. multiple dispatch) — это механизм, позволяющий выбрать одну из нескольких функций в зависимости от динамических типов аргументов. Таким образом, в отличие от обычных виртуальных функций выбор осуществляется с учетом не одного типа объекта, а нескольких. А в отличие от статической перегрузки функций выбор осуществляется на основе информации о динамических типах аргументов.
Является обобщением понятий виртуальной функции и статической перегрузки функций.
Примеры
C++
/* Example using run time type comparison */ void Asteroid::collide_with(Thing * other) { Asteroid * other_asteroid = dynamic_cast<Asteroid*>(other); if (other_asteroid) { // deal with asteroid hitting asteroid return; } Spaceship * other_spaceship = dynamic_cast<Spaceship*>(other); if (other_spaceship) { // deal with asteroid hitting spaceship return; } } void Spaceship::collide_with(Thing * other) { Asteroid * other_asteroid = dynamic_cast<Asteroid*>(other); if (other_asteroid) { // deal with spaceship hitting asteroid return; } Spaceship * other_spaceship = dynamic_cast<Spaceship*>(other); if (other_spaceship) { // deal with spaceship hitting spaceship return; } }
или:
/* Example using polymorphism and method overloading */ void Asteroid::collide_with(Thing * other) { other->collide_with(this); } void Asteroid::collide_with(Asteroid * other) { // deal with asteroid hitting asteroid } void Asteroid::collide_with(Spaceship * other) { // deal with asteroid hitting spaceship } void Spaceship::collide_with(Thing * other) { other->collide_with(this); } void Spaceship::collide_with(Spaceship * other) { // deal with spaceship hitting spaceship } void Spaceship::collide_with(Asteroid * other) { // deal with spaceship hitting asteroid }
Ссылки
- Клюев, Александр (19 июля 2003) Мультиметоды и С++ RSDN Magazine #2-2003 . Проверено 11 июня 2006 г.