Search code examples
c++templatesglobal-variablesstatic-variables

How to implement static variable functionality for templates in C++


I'm dealing with a design dilemma and would appreciate your thoughts. I have implemented a template class PacketManager which implements the functionality of a resource manager for different types of packets given as a template. For every TYPE of packet, I have just one instance (singleton) and I want to have a counter to count the number of PacketManager instances generated for different types of packet (so essentially count the number of packet types in the system). Naturally for that, one would use a static int variable and increment it for every instantiation. However for templates I can't have just one static variables for all template instances. Instead I have one static variable per packet type. Can you guys think of a clean solution where I can get the functionality I need? Only solution comes to my mind is to have a global variable defined which is not ideal.


Solution

  • This is a false premise:

    However for templates I can't have just one static variables for all template instances.

    Yes you can:

    #include <iostream>
    
    struct Base {
        static int counter;
        Base() { counter++; }
    };
    
    int Base::counter = 0;
    
    template <typename T> 
    struct Foo : Base {};
    
    int main(int argc, char** argv) {
        Foo<int> x;
        Foo<double> y;
        Foo<float> z;
        std::cout << Base::counter;
    }
    

    Output:

    3
    

    Actually this isn't something specific to your current problem. In general anything not depending on the template parameter can be moved to a non-template base class.