mats
mats

Reputation: 1828

Polymorphism by function parameter

Ok - this may be a very stupid question, but it's been bothering me.

Is there a language where

class Animal;
class Ape : public Animal
{...}

void doStuff(Animal* animalPtr)
{
    cout << "doing animal stuff" << endl;
}

void doStuff(Ape* apePtr)
{
    cout << "doing ape stuff" << endl;
}

Animal *ape = new Ape();
doStuff(ape);

would yield "doing ape stuff"? (please bear with me using C++ syntax) To clarify, I want "a function that accepts an argument and acts on it according to the type of the argument".

And would it make sense? Of course, as a developer you'd need to take care since instances that look just like an Animal pointer might actually call Ape code, because at runtime it's an Ape instance being pointed to.

Upvotes: 12

Views: 9144

Answers (5)

mloskot
mloskot

Reputation: 38872

Take a look at the Visitor pattern

Upvotes: 7

MSN
MSN

Reputation: 54554

Open Multi-Methods for C++, by Peter Pirkelbauer, Yuriy Solodkyy, and Bjarne Stroustrup.

This paper discusses a language extention to integrate multi-methods into C++ along with some very interesting implementation details, such as dealing with dynamically loaded libraries and the actual layout for dispatching properly. Note that it is not yet part of the C++ standard, and probably not a part of any major compiler.

Upvotes: 1

Steven Schlansker
Steven Schlansker

Reputation: 38526

Yes, there are! This is called multiple dispatch. The Wikipedia article is very good. Sadly, it seem to only be supported via language extensions for most popular languages, but there are a few (mostly esoteric) languages which support it natively.

Upvotes: 7

D.C.
D.C.

Reputation: 15588

There is some inconsistency here that is confusing. Do you want a function that accepts an argument and acts on it according to the type of the argument? This wouldn't really be polymorphism as the functions are on their lonesome, they aren't methods belonging to a class or interface hierarchy. In other words, its kindof like mixing OO paradigms with procedural paradigms.

If it is the type you want to parameterize and not the variable, you would use something like Java Generics. With generics you can inform a method that the type of the parameter coming in will also be variable. The method acts on the variable type in a generic fashion.

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798516

Potentially, but it would not be C++ since the function overloading lookups in C++ are done at compile-time, not runtime as would be required here. It would require a dynamic language that allows type-hinting and overloading.

Upvotes: 1

Related Questions