03.12.2012 Views

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

7.5. FROM MONOMORPHIC TO POLYMORPHIC BEHAVIOR 217<br />

Parametric Polymorphism<br />

Parametric polymorphism was the first type of polymorphism developed, and first identified by<br />

Christopher Strachey in 1967. It was also the first type of polymorphism to appear in an actual<br />

programming language, ML in 1976. It exists in <strong>C++</strong>, Standard ML, Haskell, and others. The<br />

term static polymorphism is often found.<br />

In <strong>C++</strong>, this type of polymorphism can be used via templates and also lets a value have more<br />

than one type. Inside<br />

template double function(T param) {..}<br />

param can have any type that can be substituted inside function to render compilable code.<br />

This is called implicit interface in contrast to a base class’s explicit interface. It achieves the<br />

same goal of polymorphism - writing code that operates on multiple types but in a very different<br />

way.<br />

To tie up to the dynamic polymorphic by example, the same example as in the static polymorphic<br />

world is used through function templates:<br />

#include<br />

class topology<br />

{<br />

// ... temp class<br />

};<br />

class structured vertex<br />

{<br />

public:<br />

structured vertex(int id, topology∗ topo) : id(id), topo(topo) {}<br />

bool equal(const structured vertex& ve) const<br />

{<br />

return id == ve.id && topo == ve.topo;<br />

}<br />

protected:<br />

int id;<br />

topology∗ topo;<br />

};<br />

class unstructured vertex<br />

{<br />

public:<br />

unstructured vertex(int handle, topology∗ topo, int segment) : handle(handle), segment(segment), topo(topo) {}<br />

bool equal(const unstructured vertex& ve) const<br />

{<br />

return handle == ve.handle && topo == ve.topo && segment == ve.segment;<br />

}

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!