Non-const static members in templates?

D

Derek

Here is a simple template with a non-const static data member:

template <typename T>
class Foo
{
public:
static int bar;
};

template <typename T> int Foo<T>::bar = 42;

What I want to know is how the compiler/linker guarantees there
will only be one Foo<T>::bar for each possible T? I assume the
compiler generates storage for Foo<T>::bar in every translation
unit that instantiates Foo<T> and tasks the linker with stripping
any duplicates?
 
V

Victor Bazarov

Derek said:
Here is a simple template with a non-const static data member:

template <typename T>
class Foo
{
public:
static int bar;
};

template <typename T> int Foo<T>::bar = 42;

What I want to know is how the compiler/linker guarantees there
will only be one Foo<T>::bar for each possible T? I assume the
compiler generates storage for Foo<T>::bar in every translation
unit that instantiates Foo<T> and tasks the linker with stripping
any duplicates?

Probably. How does the compiler guarantee that there is only one
instance of a member function, for example? The same way, most likely.

If you really want to know the inner workings of a compiler, I'd look
at the source for G++ (it's open source, isn't it?) or asked in
comp.compilers.

V
 
J

Jonathan Turkanis

Derek said:
Here is a simple template with a non-const static data member:

template <typename T>
class Foo
{
public:
static int bar;
};

template <typename T> int Foo<T>::bar = 42;

What I want to know is how the compiler/linker guarantees there
will only be one Foo<T>::bar for each possible T? I assume the
compiler generates storage for Foo<T>::bar in every translation
unit that instantiates Foo<T> and tasks the linker with stripping
any duplicates?

There is a good discussion in C++ Templates: The Complete Guide, starting on p.
153 ("Implementation Schemes")

Jonathan
 
D

Derek

Jonathan said:
There is a good discussion in C++ Templates: The Complete Guide,
starting on p. 153 ("Implementation Schemes")

Thanks for the tip, Jonathan. My library at work has a copy of
"C++ Templates" and I'm reading that section right now.
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top