Wednesday, November 3, 2010

Initializing a Static Member Variable within a Templated Class which relies upon Template Parameters

I ran into a tree today...

I was writing this wonderful foo class and everything was going well, but then I encountered an interesting problem.

Bad
template<class T> class foo { static T bar; };

How can I properly initialize bar?

In order to initialize a static member variable in a templated class, you need to include the initialization within the class's header file along with the class's template definition.

Some code should speak louder than words...

Good
template<class T> class foo { static T bar; }; template<class T> T foo::bar = value;

You need to include the initialization within the header file because the compiler needs a templated class's complete definition whenever it's used, and the compiler can't know that the static member variable was ever initialized if its buried in some other .cpp file.

You need to include the template definition of the class because it looks strange otherwise. Realistically, I'm pretty sure, the compiler would do just fine without the information (it could retrieve it itself easily enough), but I figure that when the standard was being crafted they looked at both options and decided that it looked strange without.

No comments:

Post a Comment