Mikarnage
Mikarnage

Reputation: 893

Uninvasive polymorphism

A simple C++ question : is it possible to call a function or another based on the runtime type of a pointer?

For example I have a class A, and class B is a child of A.

I want to write a function f such that

f(A* a)
{//do something
}
f(B* b)
{//do something else
}

//call f()
A* a = new A();
A* b = new B();
f(a);//do something
f(b);//do something, but I'd like it to "do something else"

Additional precision : A and B are defined and instanced out of my code, so I can't use regular polymorphism with virtual functions on A and B...

I know you can use some RTTI, but is there a more elegant solution?

Upvotes: 4

Views: 199

Answers (4)

Nemanja Trifunovic
Nemanja Trifunovic

Reputation: 24561

If I understand your question correctly, you are looking for multimethods. C++ doesn't provide multimethods as a language feature although there is an experimental extension, written by Bjarne Stroustrup. You can use the Visitor pattern as a workaround. A very detailed article on multimethods in C++: MultiMethods in C++: Finding a complete solution

Upvotes: 0

Andriy
Andriy

Reputation: 8604

You may achieve that using dynamic_cast:

f(A* a)
{
B* b = dynamic_cast<B*>(a);
if (b == nullptr)
//do something
else
//do something else
}

Upvotes: 5

Cubic
Cubic

Reputation: 15683

That has nothing to do with polymorphism. f(A*) and f(B*) aren't the same function, they just happen to have the same identifier. The compiler will pick which one to use. Without RTTI of some sort you can't do this in C++.

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258618

With those constraints (can't modify the classes), and without using RTTI, no.

You could use a decorator pattern, wrap A and B in some other classes and make f take those as parameters, but that seems like overkill.

Upvotes: 5

Related Questions