www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/04/21/18:30:25

From: Davin Max Pearson <d DOT pearson AT ext DOT canterbury DOT ac DOT nz>
Newsgroups: comp.os.msdos.djgpp
Subject: Can you do this using templates?
Date: 22 Apr 1998 10:16:24 +1200
Organization: University of Canterbury
Lines: 86
Message-ID: <wkn2deakhz.fsf@wibble.zibble>
NNTP-Posting-Host: exti141.tacacs.canterbury.ac.nz
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

I am writing a generic Doubly-linked list (eg: HillList, TrackList,
MessageList) that requires the following two classes to be generated
for each instantiation (eg: Hill, Track, Message etc.)

This construct can be written using the preprocessor like so: (this
code works)

#define INSTANTIATE(A,B,C)                      \
class A;                                        \
class B;                                        \
                                                \
class A {                                       \
public:                                         \
   B* b;                                        \
   C  c;                                        \
};                                              \
class B {                                       \
public:                                         \
   A* a;                                        \
   C  c;                                        \
};

INSTANTIATE(A,B,int);

A a;
B b;

int main()
{
   a.c = 43;
   a.b = &b;
   b.a = &a;
   b.c = 1;
}

What I am wondering is: Can you do this using templates?  It would be
slightly more elegant if templates could be used, rather than the
preprocessor, since the preprocessor is supposed to be obsolete!  I
would also expect slightly faster compilations if templates rather
than the preprocessor could be used.

The following is how you might expect the templatized version to
appear:

template<class B, class C>
class A {
public:
   B* b;
   C  c;
};

template<class A, class C>
class B {
public:
   A* a;
   C  c;
};

But the problem is that it is impossible to instantiate this template,
since each requires the other to already exist!  

Remember how C has a declaration like: struct A; which allows you to
have two classes each containing references to the other class, like
so: 

struct A;
struct B;

struct A {
  B* b;
  /* other members */
};

struct B {
  A* a;
  /* other members */
};


What I need is an equivalent expression for templates, but I cannot
work out how to do this.

Methinks that I have discovered an oversight in the template concept,
and so the preprocessor must be used... 

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019