473,804 Members | 3,049 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

recurring template problem

I've been reading (and using the examples in) Thinking in C++ (vol 2).

One of the things that the author shows you can do with templates is
the following:

#include <iostream>
using namespace std;

template<class T>
class Counted
{
static int count;
public:
Counted() { ++count; }
Counted(const Counted<T>&) { ++count; }
~Counted() { --count; }
static int getCount() { return count; }

};

template<class T>
int Counted<T>::cou nt = 0;

// Curious class definitions
class CountedClass : public Counted<Counted Class> {};
class CountedClass2 : public Counted<Counted Class2> {};

int main()
{
CountedClass a;
cout << CountedClass::g etCount() << endl; // 1
CountedClass b;
cout << CountedClass::g etCount() << endl; // 2
CountedClass2 c;
cout << CountedClass2:: getCount() << endl; // 1 (!)
} ///:~

I've tried adapting this idea to the following class that I've
used/created to try out some other things (Below is the almost working
example).

Header file:
[code]
#ifndef ID_CLASS_H
#define ID_CLASS_H

#include <map>

// magic number defines
#define NOT_A_VALID_ID -1

template<class T>
class ID_Class
{
private:
static std::map<int, int> ID_Map;
int ID_Value;

void DecrementRefere nce();
void IncrementRefere nce();

public:
// Only reason to ever NOT use the default constructor is when you
read
// the IDs from a source instead of creating new IDs.
ID_Class(int tID);
ID_Class();
~ID_Class();

ID_Class(const ID_Class<T>& Right);
ID_Class<T>& operator= (const ID_Class<T>& Right);

int Get_ID() const;

// Test/debug functions below this comment
void DumpMap() const;
};

#endif

cpp:
#include "ID_Class.h "

#include <stdexcept>
#include <ostream>
// note that #include <map> has been defined in the header. This is
needed
// for the static definition used there.

using std::cout;
using std::overflow_e rror;
using std::bad_alloc;
using std::pair;
using std::map;

template<class T>
map<int, int> ID_Class<T>::ID _Map;

// private functions
template<class T>
void ID_Class<T>::De crementReferenc e()
{
map<int,int>::i terator it = ID_Map.find(ID_ Value);
--(it->second);
if ( it->second < 1)
{
ID_Map.erase(it );
}
}

template<class T>
void ID_Class<T>::In crementReferenc e()
{
map<int,int>::i terator it = ID_Map.find(ID_ Value);
++(it->second);
if (it->second < 1)
{
throw overflow_error( "To many copies exist");
}
}

// public functions
template<class T>
ID_Class<T>::ID _Class(int tID)
{
ID_Value = tID;
if ((ID_Map.insert (pair<int,int>( ID_Value,1))).s econd == false)
{
throw bad_alloc();
}
}

template<class T>
ID_Class<T>::ID _Class()
{
ID_Value = 1;
map<int,int>::c onst_iterator it (ID_Map.begin() );
map<int,int>::c onst_iterator itEnd (ID_Map.end());

while(( it != itEnd) && (ID_Value == (*it).first))
{
++ID_Value;
++it;
}
if (ID_Value < 1)
{
throw overflow_error( "Requested negative ID");
}
if ((ID_Map.insert (pair<int,int>( ID_Value,1))).s econd == false)
{
throw bad_alloc();
}
}

template<class T>
ID_Class<T>::~I D_Class()
{
DecrementRefere nce();
}

template<class T>
ID_Class<T>::ID _Class(const ID_Class<T>& Right)
{
ID_Value = Right.ID_Value;
IncrementRefere nce();
}

template<class T>
ID_Class<T>& ID_Class<T>::op erator= (const ID_Class<T>& Right)
{
DecrementRefere nce();
ID_Value = Right.ID_Value;
IncrementRefere nce();
return *this;
}

template<class T>
int ID_Class<T>::Ge t_ID() const
{
return ID_Value;
}

// Test/Debug functions below this comment
template<class T>
void ID_Class<T>::Du mpMap() const
{
map<int,int>::c onst_iterator it (ID_Map.begin() );
map<int,int>::c onst_iterator itEnd (ID_Map.end());
while (it != itEnd)
{
cout << "ID " << (*it).first << " Has " << (*it).second << " copies"
<< endl;
++it;
}
}

main.cpp:

#include "ID_Class.h "
#include <iostream>

using namespace std
class MainID : public ID_Class<MainID >
{
};

int main( int argc, char* argv[])
{
// MainID TestID;

char t;
cin.get(t);
return(0);
};

I know that I'm missing something here since the code will compile
without a warning but when I uncomment // Main TestID; I get
unresolved externals (ctor & dtor). The question is what is is that am
I missing? What rules am I trying to break? And is there a way around
the problem?
Jul 22 '05 #1
4 1504

"velthuijse n" <ve*********@ho tmail.com> wrote in message
news:e5******** *************** ***@posting.goo gle.com...
I've been reading (and using the examples in) Thinking in C++ (vol 2).

One of the things that the author shows you can do with templates is
the following:
[snip]
I know that I'm missing something here since the code will compile
without a warning but when I uncomment // Main TestID; I get
unresolved externals (ctor & dtor). The question is what is is that am
I missing? What rules am I trying to break? And is there a way around
the problem?


It's the old, old problem. Put all your template code in the header file,
that's where it belongs. I'm surprised Bruce Eckel didn't explain that in
his book, but here it is in the FAQ.

http://www.parashift.com/c++-faq-lit...templates.html

questions 34.12 to 34.15

john
Jul 22 '05 #2

"velthuijse n" <ve*********@ho tmail.com> wrote in message
news:e5******** *************** ***@posting.goo gle.com...
I've been reading (and using the examples in) Thinking in C++ (vol 2).

One of the things that the author shows you can do with templates is
the following:
[snip]
I know that I'm missing something here since the code will compile
without a warning but when I uncomment // Main TestID; I get
unresolved externals (ctor & dtor). The question is what is is that am
I missing? What rules am I trying to break? And is there a way around
the problem?


It's the old, old problem. Put all your template code in the header file,
that's where it belongs. I'm surprised Bruce Eckel didn't explain that in
his book, but here it is in the FAQ.

http://www.parashift.com/c++-faq-lit...templates.html

questions 34.12 to 34.15

john
Jul 22 '05 #3
"John Harrison" <jo************ *@hotmail.com> wrote in message news:<c4******* ******@ID-196037.news.uni-berlin.de>...
"velthuijse n" <ve*********@ho tmail.com> wrote in message
news:e5******** *************** ***@posting.goo gle.com...
I've been reading (and using the examples in) Thinking in C++ (vol 2).

One of the things that the author shows you can do with templates is
the following:
[snip]

I know that I'm missing something here since the code will compile
without a warning but when I uncomment // Main TestID; I get
unresolved externals (ctor & dtor). The question is what is is that am
I missing? What rules am I trying to break? And is there a way around
the problem?


It's the old, old problem. Put all your template code in the header file,
that's where it belongs. I'm surprised Bruce Eckel didn't explain that in
his book, but here it is in the FAQ.


He did. In his first book, chapter 16. Guess this is what I get when I
just copy/paste existing files instead of trying to remember all the
excercises he'd suggested.

http://www.parashift.com/c++-faq-lit...templates.html

questions 34.12 to 34.15

Jul 22 '05 #4
"John Harrison" <jo************ *@hotmail.com> wrote in message news:<c4******* ******@ID-196037.news.uni-berlin.de>...
"velthuijse n" <ve*********@ho tmail.com> wrote in message
news:e5******** *************** ***@posting.goo gle.com...
I've been reading (and using the examples in) Thinking in C++ (vol 2).

One of the things that the author shows you can do with templates is
the following:
[snip]

I know that I'm missing something here since the code will compile
without a warning but when I uncomment // Main TestID; I get
unresolved externals (ctor & dtor). The question is what is is that am
I missing? What rules am I trying to break? And is there a way around
the problem?


It's the old, old problem. Put all your template code in the header file,
that's where it belongs. I'm surprised Bruce Eckel didn't explain that in
his book, but here it is in the FAQ.


He did. In his first book, chapter 16. Guess this is what I get when I
just copy/paste existing files instead of trying to remember all the
excercises he'd suggested.

http://www.parashift.com/c++-faq-lit...templates.html

questions 34.12 to 34.15

Jul 22 '05 #5

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

Similar topics

5
2253
by: papi1976 | last post by:
Hello to everyone I heard about a strange thing about wich i have'nt find anything on the net or books, someone called this "Curiously recursive pattern" or a strange trick to play with templates and inheritance... Dunno what is that or how it works :( Does someone has any idea about this thing???
14
2589
by: John Harrison | last post by:
The following code does not compile template <class Derived> struct X { typedef typename Derived::type type; }; struct Y : public X<Y> {
4
313
by: velthuijsen | last post by:
I've been reading (and using the examples in) Thinking in C++ (vol 2). One of the things that the author shows you can do with templates is the following: #include <iostream> using namespace std; template<class T> class Counted
15
3088
by: iuweriur | last post by:
A few questions on the curiously recurring template pattern: This page: http://c2.com/cgi/wiki?CuriouslyRecurringTemplate this part: template<typename T> struct ArithmeticType { T operator + (const T& other) const {
4
1495
by: Martin MacRobert | last post by:
Hi Gang, The following code does not compile, but I can't figure out why. The compiler complains that the CuriouslyDerivedType (CRDerived) does not publish the "value_type", yet in fact the class CRDerived does. Is there any way of making the code work? I would like functions to accept a CRBase template, and the CRBase must be able to deduce the "value_type" of the function that it is "curiously calling". Thanks.
1
2429
by: steve | last post by:
Hi All I am writing a program for a gymnasium for membership control It is the first time I have had to deal with appointment diaries and I want to know the best way to store recurring appointments 1. Do I calculate and save all future appointments as table records at the time of creation of the Recurring appointment or .. 2. Do I just save the details and create the appointments in code whenever
4
3102
by: chsalvia | last post by:
The "Curiously Recurring Template Pattern" (CRTP) recently caught my attention as a nice trick which allows static polymorphism. In other words, it lets you build extensible classes without the overhead of virtual function calls. (But of course, with the limitation of compile-time resolving.) Basically, you create a templated Base Class which defines an interface function that uses a static_cast to call a member function in Derived. ...
0
10562
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
10319
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9132
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6845
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();...
0
5508
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5639
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4282
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
3803
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2978
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.