Templates with static member in header file

  • Thread starter Leroy van Engelen
  • Start date
L

Leroy van Engelen

Hi group,

Say, I wanted to create a class like the following:

template < typename T >
struct Foo {
static T *bar;
};

template < typename T > T *Foo< T >::bar = 0;

And then use it like this:

int n;
Foo< int >::bar = &n;

This will work ok if done within a single .cpp file. But to be really
useful such a class should be put in a header file. However, this will
not work: because the class is a template, its implementation should be
completely put inside the header, but the static variable, bar, needs to
be declared inside an object file. This is not possible however, because
the type (and thus the storage size) of this variable depends on the
template argument and thus cannot be known in advance.

It is possible to put the following in _one_ (no more, no less!!!) of
the .cpp files to circumvent the problem:

template <> int *Foo< int >::bar = 0;

This is rather ugly: the client of the code is now exposed to
implementation details. Not good!

My question: is there nice, clean answer to this problem?

I hope I've explained it good enough :)

Thanks,

-Leroy
 
V

Victor Bazarov

Leroy van Engelen said:
Say, I wanted to create a class like the following:

template < typename T >
struct Foo {
static T *bar;
};

template < typename T > T *Foo< T >::bar = 0;

And then use it like this:

int n;
Foo< int >::bar = &n;

This will work ok if done within a single .cpp file. But to be really
useful such a class should be put in a header file. However, this will
not work: because the class is a template, its implementation should be
completely put inside the header, but the static variable, bar, needs to
be declared inside an object file.

I think you're overcomplicating the issue. There is no 'variable bar'.
There is only a _template_ of it. Yes, you will declare it in the header,
so damn what? It will not be instantiated until it's needed, and then,
the compiler is responsible of _merging_ all the instantiations into one
and the same (to satisfy the ODR), so, whenever you use Foo<int>::bar,
_all_ modules should refer to the same _instance_ of the static member.

Have you actually tried it, or are you just speculating that it won't work?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,148
Messages
2,570,838
Members
47,385
Latest member
Joneswilliam01

Latest Threads

Top