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.

218 CHAPTER 7. EFFECTIVE PROGRAMMING: THE POLYMORPHIC WAY<br />

protected:<br />

int handle;<br />

int segment;<br />

topology∗ topo;<br />

};<br />

Here, no class hierarchy is required. It has only be guaranteed, that each data type provides an<br />

implementation of the required method. Below print equal() is written as a function template:<br />

template<br />

void print equal(const VertexType& ve1, const VertexType& ve2)<br />

{<br />

std::cout ≪ std::boolalpha ≪ ve1.equal(ve2) ≪ std::endl;<br />

}<br />

In the code snippet below, the same polymorphic behavior can be seen as in the dynamic<br />

polymorphism example, but without the necessity of inheriting from a common base class.<br />

int main()<br />

{<br />

topology the topo;<br />

}<br />

// ∗∗∗ structured<br />

structured vertex sv1(12, &the topo);<br />

structured vertex sv2(12, &the topo);<br />

print equal(sv1, sv2);<br />

// ∗∗∗ unstructured<br />

unstructured vertex usv1(12, &the topo,1);<br />

unstructured vertex usv2(12, &the topo,2);<br />

print equal(usv1, usv2);<br />

return 0;<br />

Without a pointer mechanisms the compiler can easily optimize these lines, i.e. inline the code.<br />

Additionally exceptions cannot occur at run time.<br />

Due to its characteristics, static polymorphism in <strong>C++</strong> is best at:<br />

• Uni<strong>for</strong>m manipulation based on syntactic and semantic interface: Types that obey a<br />

syntactic and semantic interface can be treated uni<strong>for</strong>mly.

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

Saved successfully!

Ooh no, something went wrong!