Storing C++ templated objects as same type
        Posted  
        
            by 
                JaredC
            
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by JaredC
        
        
        
        Published on 2011-01-08T15:55:14Z
        Indexed on 
            2011/01/08
            17:54 UTC
        
        
        Read the original article
        Hit count: 221
        
I have a class that is a core component of a performance sensitive code path, so I am trying to optimize it as much as possible. The class used to be:
class Widget
{
    Widget(int n) : N(n) {}
    .... member functions that use the constant value N ....
    const int N;                // just initialized, will never change
}
The arguments to the constructor are known at compile time, so I have changed this class to a template, so that N can be compiled into the functions:
template<int N>
class Widget
{
   .... member functions that use N ....
}
I have another class with a method:
Widget & GetWidget(int index);
However, after templating Widget, each widget has a different type so I cannot define the function like this anymore. I considered different inheritance options, but I'm not sure that the performance gain from the template would outweigh the cost of inherited function invocations.
SO, my question is this:
I am pretty sure I want the best of both worlds (compile-time / run-time), and it may not be possible. But, is there a way to gain the performance of knowing N at compile time, but still being able to return Widgets as the same type?
Thanks!
© Stack Overflow or respective owner