paint-brush
Shared Static Variable for All Template Class Instancesby@drodil
2,382 reads
2,382 reads

Shared Static Variable for All Template Class Instances

by Heikki HellgrenSeptember 28th, 2018
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

<em>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 </em><a href="https://medium.com/@drodil/c-telltales-series-3a8c74a31629" target="_blank"><em>here</em></a><em>!</em>

People Mentioned

Mention Thumbnail

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - Shared Static Variable for All Template Class Instances
Heikki Hellgren HackerNoon profile picture

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.