Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I don't see why you'd need the template method pattern.</p> <p>Why not just define those algorithms as functors that can be passed to your benchmarking function?</p> <pre><code>struct BinarySearch { // functor implementing a specific search algorithm template &lt;typename iter_type&gt; void operator()(iter_type first, iter_type last){ ....} }; template &lt;typename data_type, typename search_type&gt; void BenchmarkSearch(data_type&amp; data, search_type search){ // general benchmarking/bookkeeping function // init timer search(data); // compute elapsed time } </code></pre> <p>and then call it like this:</p> <pre><code>int main(){ std::vector&lt;int&gt; vec; vec.push_back(43); vec.push_back(2); vec.push_back(8); vec.push_back(13); BenchmarkSearch(vec, BinarySearch()); BenchmarkSearch(vec, LinearSearch()); // assuming more search algorithms are defined BenchmarkSearch(vec, SomeOtherSearch(); } </code></pre> <p>Of course, another approach, which is a bit closer to what you initially wanted, could be to use <a href="http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern" rel="nofollow noreferrer">CRTP</a> (A pretty clever pattern for emulating virtual functions at compile-time - and it works with static methods too):</p> <pre><code>template &lt;typename T&gt; struct SearchBase { // base class implementing general bookkeeping static void Search() { // do general bookkeeping, initialize timers, whatever you need T::Search(); // Call derived search function // Wrap up, do whatever bookkeeping is left } } struct LinearSearch : SearchBase&lt;LinearSearch&gt; // derived class implementing the specific search algorithms { static void Search(){ // Perform the actual search } }; </code></pre> <p>Then you can call the static functions:</p> <pre><code>SearchBase&lt;LinearSearch&gt;::Search(); SearchBase&lt;BinarySearch&gt;::Search(); SearchBase&lt;SomeOtherSearch&gt;::Search(); </code></pre> <p>As a final note, it might be worth mentioning that both of these approaches should carry zero overhead. Unlike anything involving virtual functions, the compiler is fully aware of which functions are called here, and can and will inline them, resulting in code that is just as efficient as if you'd hand-coded each case.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload