473,666 Members | 1,977 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Static member variables in template class.

When you have a template class with a static member variable, ie.,

template<typena me T>
class handle
{
public:
static void* id() { return &id_; }
private:
static int id_;
};

template<typena me T> int handle<T>::id_ = 0;

the compiler is supposed to ensure that for "each" typename T, there
is one and only one copy of the static "id_" variable.

In practice however, how widely is this implemented properly?

I know that in the past some compilers wouldn't event create the
space for the static "id_" variable and it was necessary to explicitly
define them in one spot. For example, it would have been necessary
to enumerate for all T of interest, something like:

int unique<int>::id _ = 0;
int unique<float>:: id_ = 0;

Are things better now than they used to be? Are there any modern
compilers which still have strange caveats like this?

What I am hoping to be able to do is to use the address of that static
variable as a unique marker for a type. That is:

template<typena me T> void* id1() { return handle<T>::id() ; }

cout << "marker<int > = " << id1<int>() << endl;

There is also a simpler version one could write:

template<typena me T> void* id2() { static int i = 0; return &i; }

But how portable are such constructs across currently available and
not so current compilers? Can use of shared libraries/dlls complicate
the issue?

Thanks in advance.
Jul 22 '05 #1
4 3128
Graham Dumpleton wrote:
When you have a template class with a static member variable, ie.,

template<typena me T>
class handle
{
public:
static void* id() { return &id_; }
private:
static int id_;
};

template<typena me T> int handle<T>::id_ = 0;

the compiler is supposed to ensure that for "each" typename T, there
is one and only one copy of the static "id_" variable.

In practice however, how widely is this implemented properly?


I know that gcc 2.95 doesn't do it properly, but 3.0 and up does. I
can't tell anything about other compilers.

Jul 22 '05 #2
Rolf Magnus <ra******@t-online.de> wrote in message news:<c1******* ******@news.t-online.com>...
Graham Dumpleton wrote:
When you have a template class with a static member variable, ie.,


Currently on darwin (and I saw this on windows at one point) you'll
get a separate instance per shared library. On linux with g++, it
works as you would hope (and possibly expect).

The trick to making this work is to make the static member variable be
a pointer and be prepared to separately initialize each copy to point
to the same single object. For example, the first time you go to
access this static member variable pointer, be prepared for it to be
NULL, and then rather than calling new, go to some centralized library
routine which is responsible for seeing if you're the first one to
access the underlying object you really want. If so, it gets new'd up
and handed back to you, and you make *your* version of the static
member teamplte pointer point at this new object. Otherwise, you're
not the first, so you don't do a new, but you still get back a pointer
and set the static tempalte member pointer to point to the object.

As the C++ lawyers will tell you, "if it involves shared libraries,
it's outside the C++ standard."

Which effectively means just about everything is outside the standard
these days...
Jul 22 '05 #3
de*@pixar.com (David Baraff) wrote in message news:<37******* *************** ****@posting.go ogle.com>...
Rolf Magnus <ra******@t-online.de> wrote in message news:<c1******* ******@news.t-online.com>...
Graham Dumpleton wrote:
When you have a template class with a static member variable, ie.,

Currently on darwin (and I saw this on windows at one point) you'll
get a separate instance per shared library. On linux with g++, it
works as you would hope (and possibly expect).

The trick to making this work is to make the static member variable be
a pointer and be prepared to separately initialize each copy to point
to the same single object. For example, the first time you go to
access this static member variable pointer, be prepared for it to be
NULL, and then rather than calling new, go to some centralized library
routine which is responsible for seeing if you're the first one to
access the underlying object you really want. If so, it gets new'd up
and handed back to you, and you make *your* version of the static
member teamplte pointer point at this new object. Otherwise, you're
not the first, so you don't do a new, but you still get back a pointer
and set the static tempalte member pointer to point to the object.


Unfortunately one doesn't have a string or otherwise to use as the
key in allocating the handle in the centralised repository. This is
because I am trying to have that be automatically bound to the type
of the parameter to the template without special user intervention
to supply a string which identifies the type. If the user was required
to supply the string, wouldn't need the template at all for what I had
in mind.

Anyway, in terms of what I was trying to achieve, I have come across
other problems and so have to do it a totally different and more
verbose way after all.

Thanks though, it confirms my suspicion that it may not have been
portable.
As the C++ lawyers will tell you, "if it involves shared libraries,
it's outside the C++ standard."

Which effectively means just about everything is outside the standard
these days...


And we better make sure we don't top post either. ;-)
Jul 22 '05 #4
gr*****@dscpl.c om.au (Graham Dumpleton) wrote in message news:> Unfortunately one doesn't have a string or otherwise to use as the
key in allocating the handle in the centralised repository. This is
because I am trying to have that be automatically bound to the type
of the parameter to the template without special user intervention
to supply a string which identifies the type. If the user was required
to supply the string, wouldn't need the template at all for what I had
in mind.

template <typename T>
struct Cache {
static Data* _ptr;

static Data* GetData() {
if (!_ptr) _ptr =
CentralizedRegi stry::GetOrCrea teData(typeid(T ));
return _ptr;
}
};

The routine CentralizedRegi stry::GetOrCrea teData() uses the passed in
type_info as a key, and either retrieves a previously created Data*,
or creates one for the first time and stores it under the specified
key. Either way, a Data* is returned. For each type T, the routine
is called at most once per shared library.
Jul 22 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
1626
by: Alibek | last post by:
Hello ! I have here template class with static members. and I put definition of the static member in the same ..h file where the class was declared. however, we are getting very stange errors, because static member occupy same place as some other non-static variables. and so application crashes. compiler somehow allocates same place for them.
11
4596
by: Roger Leigh | last post by:
The C++ book I have to hand (Liberty and Horvath, Teach yourself C++ for Linux in 21 Days--I know there are better) states that "static member functions cannot access any non-static member variables". However, this doesn't seem entirely correct. It also doesn't mention whether static member functions can access protected and private member data and methods (and I couldn't spot this in the FAQ). I have a class row<Row> which derives from...
16
2970
by: Eric | last post by:
I have a static class member variable as follows: struct A { static void Set (int i) { v = i; } static int& Get () { return v; } static int v; }; int A::v; // define A::v in the cpp file
7
12450
by: ank | last post by:
Hi, I was curious about how to define static data member of template class. Should I put the definition in a separate source file or in the same header file as its template class? And when this data will be initialized if it is used across many translation unit, assume that it has constructor and needs dynamic initialization? I have blindly searched for the answer but I still not thoroughly
8
2831
by: Markus Henschel | last post by:
Hello, this is a test case of something I just can't explain myself: //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include <list> typedef void (*registerfunc)(); class CMgr {
3
3170
by: Shahin Tavakoli | last post by:
Hi, I'd like to put a static member in a template class, but I don't know the syntax. I've tried out template<typename Type> class Stocker : private vector<Type> { public: static int NB;
5
3600
by: mast2as | last post by:
Hi guys Here's the class I try to compile (see below). By itself when I have a test.cc file for example that creates an object which is an instance of the class SpectralProfile, it compiles fine. 1 / Now If I move the getSpectrumAtDistance( const T &dist ) method definition in SpectralProfofile.cc let's say the compiler says core/profile.cc:199: error: `kNumBins' was not declared in this scope
17
8369
by: Juha Nieminen | last post by:
As we know, the keyword "inline" is a bit misleading because its meaning has changed in practice. In most modern compilers it has completely lost its meaning of "a hint for the compiler to inline the function if possible" (because if the compiler has the function definition available at an instantiation point, it will estimate whether to inline it or not, and do so if it estimates it would be beneficial, completely regardless of whether...
4
5815
by: aaragon | last post by:
Hi everyone, I have a linking error when using gcc4.2 and static member variables. The class template definition is something around the following: template<> class Element<L2_t: public Element_common<L2, Side<2,2 { public:
0
8445
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8356
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8871
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8640
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6198
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5664
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2771
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2011
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1776
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.