Heikki Hellgren

@drodil

Shared Static Variable for All Template Class Instances

C++ Telltales part 3:

This is third part of my C++ Telltales series where I share some tips and tricks to work with C++. Feel free to check out also other parts of the series here!

Sometimes when you have a template class you need to have a static member variable that is shared for all template class instances, no matter what template parameter(s) they are using. Easiest way to accomplish this is using inheritance. Check out the following snippet:

If the prefix_message was instead declared in the Outputter class, it would be initialized for each template parameter separately and calls to set_prefix_message would only be visible in the instances using the same exact template parameters. This might be useful sometimes but if you want to create static variable for all instances, inheritance is your way to go.

And here is the same image from my first part to get some cover photo for this article (I am still feeling lazy..):

If you liked the story, please press the ❤ button below (did you know that you can give more than one clap). Also please feel free to share this story!

About me

I am Heikki Hellgren, Software Expert and technology enthusiast working at Elektrobit Automotive. My interests are in software construction, tools, automatic testing and all the new and cool stuff like AI and autonomous driving. You can follow me on Medium and Twitter and check out my websitefor more information.

More by Heikki Hellgren

Topics of interest

More Related Stories