473,699 Members | 2,905 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Circular dependencies in Templates - better solution?

Hello everyone!

I am a newbie to C++ (~1 Week experience) and I have a few months of
experience with object-oriented languages (Objective-C). I am
currently working just for fun on a particle system.

All the particles are controlled by a "server". The server performs
all kinds of operations on them (updating, drawing etc.). The
particles (my "clients") on the other hand need to retrieve once a
while some information from their server - they need to be hooked up
to it. This works perfectly alright as long as I only have one
server-class and one client-class. However if I want to add some
subclasses and make everything more customizable I run into severe
problems. The lack of run-time dynamism caused some problems on
creating the server/client class structure.
If I use a new client-class it will most likely need a new
server-class. However its superclass already inherits a connection to
the old server-class. I would need to re-implement all the member
functions for the new server-class. In a pure dynamic language
(Smalltalk/Objective-C) I could simply ignore the static type
checking. To avoid compiler warnings I would simply cast the
object-pointers when necessary (just for cosmetic reasons).
C++ would not be C++ if it wouldn't deliver a solution for this
dilemma - Templates. When I need a new client class, I just need to
pass a new type parameter. Nice.
And C++ wouldn't be C++ if no new problems would arise. I will
demonstrate it.
My server-class implementations :
template <class GenericClient>
class ServerClass
{
public:
ServerClass()
{
clients = vector<GenericC lient> (10, GenericClient(* this));
}
protected:
vector<GenericC lient> clients;
int foo;
};

template <class GenericClient>
class ServerSubclass : public ServerClass<Gen ericClient>
{
public:
ServerSubclass( ) {}
protected:
int bar;
};
No problem until now. But now the client-class implementations :
template <class GenericServer>
class ClientClass
{
public:
ClientClass() : server(NULL) {}
ClientClass(Gen ericServer *aServer) { server = aServer; }
protected:
GenericServer *server;
};

template <class GenericServer>
class ClientSubclass : public ClientClass<Gen ericServer>
{
public:
ClientSubclass( ) {}
ClientSubclass( GenericServer *aServer) :
ClientClass<Gen ericServer>(aSe rver){}
protected:
int bla;
};
You can see that every client gets a connection to its server, when it
is constructed. But now try to instantiate a server with a
client-class.
ServerSubclass< ClientSubclass< ServerSubclass< ClientSubclass. ..> > >
We get an infinite circular dependency between the template classes.
It is impossible to solve this circular dependency unless I have
missed something fundamental about C++ templates.
However there is a not so elegant way to do it with partially
resorting to traditional OO constructions. All I need to do is to
rewrite my client-subclass without templates.
class ClientSubclass : public
ClientClass<Ser verSubclass<Cli entSubclass> >
{
public:
ClientSubclass( ) {}
ClientSubclass( ServerSubclass< ClientSubclass> *aServer) :
ClientClass<Ser verSubclass<Cli entSubclass> >(aServer) {}
protected:
int bla;
};
This looks confusing and it is indeed. But it is now possible to
instantiate a server.
ServerSubclass< ClientSubclass> myServer();
However subclassing without a template is not only a way to solve the
circular-dependency-problem but also to prevent any further
subclassing. If I wanted to subclass my first-subclass with all its
member functions I would need to convert my first subclass to a
template class and then subclass it twice (once for the first and once
for the second non-template subclass).

Am I totally wrong? Have I totally missed something about OO design?
Is there a more convenient way of doing this in C++ ?

Any comments appreciated ;-)

TIA
Robert Potthast
Jul 23 '05 #1
4 4794
ro86 wrote in news:dd******** *************** ***@posting.goo gle.com in
comp.lang.c++:

ServerSubclass< ClientSubclass< ServerSubclass< ClientSubclass. ..> > >
We get an infinite circular dependency between the template classes.
It is impossible to solve this circular dependency unless I have
missed something fundamental about C++ templates.
However there is a not so elegant way to do it with partially
resorting to traditional OO constructions. All I need to do is to
rewrite my client-subclass without templates.


What you need is template template paramiters:

#include <iostream>
#include <ostream>
#include <vector>
template < template <typename> class GenericClient >
class ServerClass
{
public:
ServerClass() :
clients(
std::vector< GenericClient< ServerClass > > (
10, GenericClient< ServerClass >(this)
)
)
{
}

void print()
{
std::size_t i, len = clients.size();
for ( i =0; i < len; ++i )
{
clients[i].print();
}
}

protected:
std::vector< GenericClient<S erverClass> > clients;
int foo;
};

template < template <typename> class GenericClient >
class ServerSubclass : public ServerClass<Gen ericClient>
{
public:
ServerSubclass( ) {}
protected:
int bar;
};
template <typename GenericServer>
class ClientClass
{
public:
ClientClass() : server(NULL) {}
ClientClass(Gen ericServer *aServer) { server = aServer; }
virtual void print() {}
protected:
GenericServer *server;
};
template <typename GenericServer>
class ClientSubclass : public ClientClass< GenericServer >
{
public:
ClientSubclass( ) {}
ClientSubclass( GenericServer *aServer) :
ClientClass< GenericServer >(aServer), bla( 0 )
{
}
ClientSubclass( ClientSubclass const &rhs ) : bla( ++rhs.bla )
{
}
virtual void print() { std::cout << bla << '\n'; }
protected:
mutable int bla;
};

ServerSubclass< ClientSubclass > server;

int main()
{
server.print();
}

HTH.

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 23 '05 #2
Rob Williscroft wrote:
template < template <typename> class GenericClient >
class ServerClass
{
//...
}
Ok, this one is not easy.
The server-class template assumes that you pass a class which is again
a template as parameter. Right?
std::vector< GenericClient< ServerClass > > (
10, GenericClient< ServerClass >(this)
I think this is the tricky part. The compiler knows that the
GenericClient awaits another class as parameter. If we would write this
outside of our template we would have a circular (or recursive)
dependency. But now we can pass the template class for our client as
parameter and thus avoid the circular dependency.
HTH.

Yes, it did ;)
Thanks!

Jul 23 '05 #3
wrote in news:11******** *************@g 14g2000cwa.goog legroups.com in
comp.lang.c++:
Rob Williscroft wrote:
template < template <typename> class GenericClient >
class ServerClass
{
//...
}
Ok, this one is not easy.
The server-class template assumes that you pass a class which is again
a template as parameter. Right?


The paramiter is template-template paramiter and it must
be passed a class-template that takes one type paramiter.
std::vector< GenericClient< ServerClass > > (
10, GenericClient< ServerClass >(this)


I think this is the tricky part. The compiler knows that the
GenericClient awaits another class as parameter. If we would write this
outside of our template we would have a circular (or recursive)
dependency. But now we can pass the template class for our client as
parameter and thus avoid the circular dependency.


Well the bit you quoted is inside a constructor, templates and there
members are only instantiated when they're needed. Before it
instantiates the constructor it will instantiate the class to do that
it needs to instantiate the data member:

std::vector< GenericClient<S erverClass> > clients;

to do that it may need to instantiate:

GenericClient<S erverClass>

Fortunatly this can be done without knowing anything about
ServerClass as neither:

ClientSubclass< ServerClass > or
ClientSubclass< ServerSubClass >

require knowing anything about ServerClass or ServerSubClass
as they only use a pointers to a ServerClass.

The terminoligy used to refere to this is "ClientSubc lass can
be instantiated with an incomplete type", ServerSubClass (and
ServerClass) being the incomplete (because they're currently
being instatiated) types.

Also I noticed that the code I posted may not do precisley
what you wanted, as the ServerSubClass contains a std::vector
of ClientSubClass< ServerClass > where as IIUC you wanted
a vector of ClientSubClass< ServerSubClass >.

Here's the fixed code, it has an extra paramiter to ServerClass
to feed in the sub-class type and a static_cast to cast from the
base type to the derived type:

#include <iostream>
#include <ostream>
#include <vector>
template < template <typename> class GenericClient, typename Server >
class ServerClass
{
public:
ServerClass() :
clients(
std::vector< GenericClient< Server > > (
10, GenericClient< Server >(static_cast < Server *>( this ) )
)
)
{
}

void print()
{
std::size_t i, len = clients.size();
for ( i =0; i < len; ++i )
{
clients[i].print();
}
}

protected:
std::vector< GenericClient< Server > > clients;
int foo;
};
template < template <typename> class GenericClient >
class ServerSubclass :
public ServerClass<Gen ericClient, ServerSubclass< GenericClient > >
{
public:
ServerSubclass( ) {}
protected:
int bar;
};
template <typename GenericServer>
class ClientClass
{
public:
ClientClass() : server(NULL) {}
ClientClass(Gen ericServer *aServer) { server = aServer; }
virtual void print() {}
protected:
GenericServer *server;
};
template <typename GenericServer>
class ClientSubclass : public ClientClass< GenericServer >
{
public:
ClientSubclass( ) {}
ClientSubclass( GenericServer *aServer) :
ClientClass< GenericServer >(aServer), bla( 0 )
{
}
ClientSubclass( ClientSubclass const &rhs ) : bla( ++rhs.bla )
{
}
virtual void print() { std::cout << bla << '\n'; }
protected:
mutable int bla;
};

ServerSubclass< ClientSubclass > server;
int main()
{
server.print();
}

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 23 '05 #4
This looks like the final solution. The original implementation hooked
the ClientSubclass to the ServerClass up. All I now need to do is to
wrap my classes into a elegant typedef and I can go on.
This has been very helpful. Problems like these are the only way to
learn more about complex languages like C++. The concept of templates
is fascinating because its very flexible but offers very high
performance (A glimpse into the future of meta-programming?). Learning
by doing =)
Danke!

Jul 23 '05 #5

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

Similar topics

12
5249
by: jinal jhaveri | last post by:
Hi All, I have one question regarding circular inheritance I have 3 files 1) A.py , having module A and some other modules 2) B.py having module B and some other modules 3) C.py having module C and some other modules
1
2094
by: Henry Miller | last post by:
I have the following code (much simplified for this post). Note that SessionKey uses DataAccess, and DataAccess requires SessionKey in it's constructor. Public Class SessionKey Public IsValidSession as Boolean Sub New(UserName, Password) ' Create session, including calls on DataAccess ' to validate username/password
3
2046
by: crichmon | last post by:
Any general advice for dealing with circular dependencies? For example, I have a situation which, when simplified, is similar to: ///////////// // A.h class A { public: int x;
2
3102
by: ernesto basc?n pantoja | last post by:
Hi everybody: I'm implementing a general C++ framework and I have a basic question about circular dependencies: I am creating a base class Object, my Object class has a method defined as: virtual String toString(); where String is defined as:
16
2000
by: PromisedOyster | last post by:
Hi I have a situation where I want to use circular referencing. I have cut down the example for demonstration purposes. Say we have one executable (main.exe) and two DLLS (A1.dll and A2.dll). Main can access classes in A1 and A2; A1 can access classes in A2. However, I now want to access classes in A1 from A2. I cannot simply create a third DLL as the A1/A2 assemblies use other classes within
3
2898
by: Keith F. | last post by:
Visual Studio doesn't allow circular references between projects. I have a situation where I need to allow 2 projects to reference each other. Is there any way to make Visual Studio allow this? I realize the best way is to restructure the solution so the circular reference isn't necessary, which I intend to do. But at the moment, I'm looking for a quicker work-around if there is one. Thanks.... Keith F.
7
13514
by: barias | last post by:
Although circular dependencies are something developers should normally avoid, unfortunately they are very easy to create accidentally between classes in a VS project (i.e. circular compile-time dependencies). But then I started wondering how "easy" it would be to similarly make a NON-RUNTIME circular dependency between (implicitly linked) DLLs. Indeed authors like John Lakos, who focus on compile/link-time dependencies (not run-time),...
8
4141
by: nyhetsgrupper | last post by:
I have written a windows service and want to expose a web based user interface for this service. I then wrote a class library containing a ..net remoting server. The class library have a method named StartRemotingServer(). To be able to call this method from the windows service I need to reference the remoting class library, but for the class library to be able to access the internal structures of the windows service the class library...
6
3469
by: Mosfet | last post by:
Hi, I have two classes, let's call them class A and class B with mutual dependencies as shown below and where implementation is inside .h (no cpp) #include "classB.h" class A {
0
8704
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
8623
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
9192
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
9054
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...
1
8940
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7781
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
4637
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2362
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2015
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.