Note that there are some explanatory texts on larger screens.

plurals
  1. POTemplates as an alternative to virtual functions in C++
    primarykey
    data
    text
    <p>I have an expensive function defined in a base class, which depends on low level information from its derived classes:</p> <pre><code>class BaseClass{ ... // Defined in derived class virtual int low_level(int)=0; // Expensive function depending on the pure virtual function void myExpensiveFunction(){ for(...){ for(...){ for(...){ ... = low_level(...); ... } } } } }; class DerivedClass : public BaseClass{ // A very cheap operation that can be inlined: inline virtual int low_level(int i){ return a[i]; } // Calling the base class function void test(){ myExpensiveFunction(); } }; </code></pre> <p>If I understand things correctly, the fact that the low-level function is virtual prevents it from being inlined in the code above. Now, I was thinking about a way to get around this and thought of the following solution, where I pass a pointer to the derived class member function as a template parameter:</p> <pre><code>class BaseClass{ ... // The function is now templated by the derived function: template&lt;typename D, int (D::*low_level)(int)&gt; void myExpensiveFunction(){ for(...){ for(...){ for(...){ ... = static_cast&lt;D*&gt;(this)-&gt;low_level(...); ... } } } } }; class DerivedClass : public BaseClass{ // A very cheap operation that can be inlined: inline int low_level(int i){ return a[i]; } // Calling the base class function void test(){ myExpensiveFunction&lt;DerivedClass,&amp;DerivedClass::low_level&gt;(); } }; </code></pre> <p>Does this strategy make sense? I imagine that the low level operation will be inlined when the expensive base class function is expanded in the derived class.</p> <p>I tested implementing it and it compiles and works, but I haven't seen any noticeable differences in performance.</p> <p>Kind regards, Joel</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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