473,791 Members | 2,881 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Template Meta Programming Techniques

I work with molecular simulations. In a normal infinate space
simulation, a particle can occupy any cartesian position in space.

If i want the distance between two particles in a system I can use:

Maths::dvector va, vb;
// Code here: Do something to initialise variables and move them around...
double distance = dist(va,vb);

I am currently looking at 'Periodic boundary simulations'. By this i
mean, I am simulating particles in a box, and when a particle goes off
one edge of the box, it comes back on the other side... Easy stuff -
very usesful in molecular dynamics.

<see example code below>

As dist(Maths::dve ctor& va, Maths::dvector& vb) is an inline function,
it has overall good performance. However if i want to now have a
'generalised' simulation class, my OOP experience tells me that I should
have a 'Space' class that manages calls like 'dist' for any arbritary
derived space system. Thus (via virtual calls) when I call getDistance()
in 'InfiniteSpace' I just call dist(), but when I call it in
'PeriodicRectan gular' it takes the 'periodic cube' into account.

My problem is therefore one of performance. When I have a pointer to an
instance of a class that derives from 'Space', the compiler can't inline
the code when getDistance() is called, so performance sux. This goes
away if you make specialised classes, but that defeats the whole point
of inheritance and being generalised.

So my question is, is there a way of giving my simulation a Template
Meta Argument e.g. Simulation<Spac e sto avoid the need to have
'virtual' all over the place. I have scratched my head and cant really
think of the best way to do this...

Any Ideas Guys??

Many Thanks For Any Comments,
Jon Rea

-------------
Example Code:
-------------

class Space {
public:
Space(){};
virtual ~Space(){};

inline virtual double getDistance(
const Maths::dvector &va,
const Maths::dvector &vb
) const = 0;
}

class InfiniteSpace: public Space {
public:
InfiniteSpace() {};
virtual ~InfiniteSpace( ){};

inline virtual double getDistance(
const Maths::dvector &va,
const Maths::dvector &vb
) const
{
return dist(va,vb);
}
}
class PeriodicRectang ular: public Space {
public:
PeriodicRectang ular(double allsize):
boxSize(allsize ,allsize,allsiz e),
halfBoxSize(box Size);

virtual ~PeriodicRectan gular(){};

inline void getVector(
const Maths::dvector &va,
const Maths::dvector &vb,
Maths::dvector &vavb
) const
{
vavb.diff(vb,va );

if(vavb.innerdo t() < sqrSaveDistance ) return;

// find closest image of vb.x;
if(vavb.x halfBoxSize.x) vavb.x -= boxSize.x;
if(vavb.x < -halfBoxSize.x) vavb.x += boxSize.x;

// find closest image of vb.y;
if(vavb.y halfBoxSize.y) vavb.y -= boxSize.y;
if(vavb.y < -halfBoxSize.y) vavb.y += boxSize.y;

// find closest image of vb.z;
if(vavb.z halfBoxSize.z) vavb.z -= boxSize.z;
if(vavb.z < -halfBoxSize.z) vavb.z += boxSize.z;
}
inline virtual double getDistance(
const Maths::dvector &va,
const Maths::dvector &vb
{
Maths::dvector vavb;
getVector(va,vb ,vavb);
return vavb.mag();
}
)

Simulate( Space* mySpace )
{
// Do some simulating ...
for( int i = 0; i < xxx; i++ )
mySpace->getDistance( blaA, blaB );
}
Oct 9 '06 #1
5 1853
Jon Rea wrote:
I work with molecular simulations. [..]

I am currently looking at 'Periodic boundary simulations'. By this i mean,
I am simulating particles in a box, and when a particle goes off one edge
of the box, it comes back on the other side... [..]
"It" comes back? Are you sure? I thought the whole point is that when
a particle leaves, it leaves forever, and *another one* comes into the
box to play.
As dist(Maths::dve ctor& va, Maths::dvector& vb) is an inline function,
it has overall good performance. However if i want to now have a
'generalised' simulation class, my OOP experience tells me that I
should have a 'Space' class that manages calls like 'dist' for any
arbritary derived space system. Thus (via virtual calls) when I call
getDistance() in 'InfiniteSpace' I just call dist(), but when I call
it in 'PeriodicRectan gular' it takes the 'periodic cube' into account.

My problem is therefore one of performance. [..]
I don't have an immediate solution for you, especially considering that
I don't have a slightest idea about molecular simulations. But if the
molecule goes outside the box, shouldn't you stop using it in your
simulation and instead use the other one (not "it"), which comes into
the box from the opposite side?

The idea here is that instead of trying to simulate the infinite space
and the infinite number of particles, you take a sample of the space,
limiting it to your box, and only use those particles that are inside
your box at any time.

If you continue trying to track those particles, you're essentially
trying to solve the same infinite space problem using the same number
of particles, only now you make it more difficult to track them.

Of course, it all could be pointless blabber, since I don't really
know squat about molecular simulations.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Oct 9 '06 #2
Jon Rea wrote:
>
So my question is, is there a way of giving my simulation a Template
Meta Argument e.g. Simulation<Spac e sto avoid the need to have
'virtual' all over the place. I have scratched my head and cant really
think of the best way to do this...
I'm not sure if this will help ... but take a look at this paper
(especially sections 1.3 and 1.3.3):
http://osl.iu.edu/~tveldhui/papers/techniques/

This is from the same webpage that you mentioned in your last post.

-- Szabolcs
Oct 9 '06 #3
Jon Rea wrote:
So my question is, is there a way of giving my simulation a Template
Meta Argument e.g. Simulation<Spac e sto avoid the need to have
'virtual' all over the place. I have scratched my head and cant really
think of the best way to do this...

Any Ideas Guys??
Hi Jon,

Why do you want to use polymorphism? Why not just use a common
functional interface? I'm a bit puzzled, because what you describe
seems to be standard stuff for the most simple usage of templates
conceivable.

As I don't know your surrounding program, it is impossible to tell
whether you want to store the space group in some global variable. In
that case boost::any would be your candidate.

Anyway, have a look at the following which should both be fast and
generic:

#include <iostream>
struct InfiniteSpace {
inline double getDistance(){s td::cout << "using infinite space\n";}
};
struct PeriodicRectang ular {
inline double getDistance(){s td::cout << "using periodic
boundaries\n";}
};
template <typename T>
void Simulate(T& t)
{
std::cout << "Calling function "<<__FUNCTION__ <<"\n";
t.getDistance() ;
};
int main() {
bool use_periodic=tr ue;
InfiniteSpace i;
PeriodicRectang ular p;
if (use_periodic)
Simulate (p);
else
Simulate (i);
}

Oct 9 '06 #4
F.J.K. wrote:
Jon Rea wrote:
>So my question is, is there a way of giving my simulation a Template
Meta Argument e.g. Simulation<Spac e sto avoid the need to have
'virtual' all over the place. I have scratched my head and cant really
think of the best way to do this...

Any Ideas Guys??

Hi Jon,

Why do you want to use polymorphism? Why not just use a common
functional interface? I'm a bit puzzled, because what you describe
seems to be standard stuff for the most simple usage of templates
conceivable.

As I don't know your surrounding program, it is impossible to tell
whether you want to store the space group in some global variable. In
that case boost::any would be your candidate.

Anyway, have a look at the following which should both be fast and
generic:

#include <iostream>
struct InfiniteSpace {
inline double getDistance(){s td::cout << "using infinite space\n";}
};
struct PeriodicRectang ular {
inline double getDistance(){s td::cout << "using periodic
boundaries\n";}
};
template <typename T>
void Simulate(T& t)
{
std::cout << "Calling function "<<__FUNCTION__ <<"\n";
t.getDistance() ;
};
int main() {
bool use_periodic=tr ue;
InfiniteSpace i;
PeriodicRectang ular p;
if (use_periodic)
Simulate (p);
else
Simulate (i);
}
The issue is this:

Avove is not quite right for my system because there's a single place
where the particular type of Space is stored: so more like this:

struct Space{
inline double getDistance(){s td::cout << "base space\n";}
};

struct InfiniteSpace:p uiblic Space {
inline double getDistance(){s td::cout << "using infinite space\n";}
};

struct PeriodicRectang ular: public Space {
inline double getDistance(){s td::cout << "using periodic
boundaries\n";}
};

template <typename T>
void Simulate(T& t)
{
std::cout << "Calling function "<<__FUNCTION__ <<"\n";
t.getDistance() ;
};

int main() {
bool use_periodic=tr ue;
InfiniteSpace i;
PeriodicRectang ular p;
Space = the_chosen_spac e;
if (use_periodic)
the_chosen_spac e = &p;
else
the_chosen_spac e = &i;

Simulate( *t );
}

now this wont work because *t is of type Space (no matter what it
actually points to) and so you'll always get the <Spaceversion of
the template function not the appropriate one (i think) - one'd have
to do a dynamic up cast ..

Am I making sense?

Cheers,
Jon
Oct 9 '06 #5
Jon Rea wrote:
F.J.K. wrote:
As I don't know your surrounding program, it is impossible to tell
whether you want to store the space group in some global variable. In
that case boost::any would be your candidate.
Avove is not quite right for my system because there's a single place
where the particular type of Space is stored: so more like this:
Actually that was what I was referring to in above sentence ;-) At this
point you have two choices. You can use boost::any and its any.type() +
anycast <>() to do the the proper typecasting. I think (but I'm only a
newbie and welcome being corrected) that RTTI and typeid() won't work,
if you don't use virtual functions, which is the whole point.

Or you can keep track of what's really in your variable yourself with
an extra variable like use_periodic and do the typecasting yourself.

Most quantum mechanical or molecular mechanics programs I know of keep
track themselves. While theoretically this allows for runtime errors,
practically it gives you total control over when and where you use
polymorphism (manually, in your if clauses) and when you can't afford
the cost. Even very old QM Fortran programs like Gaussian use
polymorphism in that sense.
now this wont work because *t is of type Space (no matter what it
actually points to) and so you'll always get the <Spaceversion of
the template function not the appropriate one (i think) - one'd have
to do a dynamic up cast ..
Am I making sense?
Yup. That's exactly what dynamic_casts<a re good for. However in
certain situations, union + static_cast would be equally good, maybe
even better. Ask yourself if there really is a common implementation
base for your Space classes. In the example you gave, there isn't. The
only thing they share is a functional interface, the availability of
the getDistance() function. In that case: don't use inheritance.

Take a look at vector<and list<>. They both implement functions like
push_back() or size(). Yet there's practically no overlap in
implementation. Consequently the STL isn't so stupid as to define a
class container<so that vector<T>:conta iner<Tand
list<T>:contain er<T>. Learn from the mistakes of the early class
libraries which did exactly this and were slow as hell and do it the
STL way :-)

#include <iostream>
struct InfiniteSpace{
double getDistance(){s td::cout << "using infinite space\n";}
};
struct PeriodicRectang ular{
double getDistance(){s td::cout << "using periodic boundaries\n";}
};
union Space {
InfiniteSpace infinite_space;
PeriodicRectang ular periodic_rectan gular;
};
template <typename T>
void Simulate(T& t)
{
std::cout << "Calling function "<<__FUNCTION__ <<"\n";
t.getDistance() ;
};
int main() {
bool use_periodic=fa lse;
Space space;
if (use_periodic)
Simulate(space. periodic_rectan gular);
else
Simulate(space. infinite_space) ;
}

Oct 10 '06 #6

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

Similar topics

12
2163
by: Dave | last post by:
Would people agree with the statement that to a large degree, using template metaprogramming techniques turns a C++ compiler into a C++ interpreter (but just for the metaprogrammed portions of the code)? It's not a perfect analogy, but it seems to be a reasonable statement...
4
2223
by: Ingo Nolden | last post by:
Hi, I want to write a template class that holds another class that uses the same template. This recursion should stop after a predefined number. I think it's either impossible or easy, but I have no idea right now :-( A simplified version is here: template< unsigned Depth > class Foo
5
2165
by: Steve | last post by:
Hi, Does C++ allow the programmer to declare a template with in a template so that a generic function can instantiate the embedded template? For example, could code such as this exist: template< class T<int N> > int func() { int the_n = N;
2
1662
by: Ganesh | last post by:
I am not sure if the question is relevant to this group. Is there a proof that template metaprogramming is Turing-complete? Is the proof trivial - just replace all the template instantiaion with a function call and since function calls are turing complete, template metaprogramming is turing complete. I am not sure if this is a valid proof. I may not even make sense, as I am not very confident when it comes to theoritical computer...
8
2285
by: Jon Rea | last post by:
http://osl.iu.edu/~tveldhui/papers/Template-Metaprograms/meta-art.html Can anyone shed some light on the need for stuff like this when using any of the most modern compilers? If i have a function : double Square( double d ) { return d * d;
35
1935
by: Steven T. Hatton | last post by:
Perhaps I'm just a bit frustrated, and I will soon realize the clear truth of the matter, but right now I have some serious misgivings about the value of investing a lot of time and effort into template programming. I just finished reading the first 12 chapters of _C++ Templates: The Complete Guide_. One thing that struck me as I read these chapters is how much I didn't know about C++. I _know_ the core language specification is...
3
3290
by: gary.bernstein | last post by:
I want to call a singleton getInstance function to retrieve a templatized object without knowing what types were used to create the singleton object in the first call to getInstance. How can I do this non-intrusively -- I.e., without, for example, typedef'ing the types in every compilation unit? Background: Our code base has assert macros that need to reboot the system after notifying components via a single templatized Component...
7
7979
by: Kevin | last post by:
I'm creating a template to support state machines. In doing so, I need to pass an enumeration for the number of transitions and a non type parameter for the range of the enum (to allow me to allocate an array of pointers big enough to hold one entry for each transition). My template declaration looks roughly like this: template <class TRANSITION, int NUMTRANSITIONS> class StateMachine { ***SNIP*** void RegisterTransition(TRANSITION...
3
1855
by: stdlib99 | last post by:
Hi, I have a simple question regarding templates and meta programming. I am going to try and work my way through the C++ Template Metaprogramming, a book by David Abrahams and Aleksey Gurtovoy. I’m not doing this because I want to be a Meta Programming guru (because a lot of that stuff looks too crazy for use in the real world). Rather I want to learn heavyweight templates and this is the only
0
9669
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
10207
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
10154
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
9993
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...
0
9029
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
6776
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
4109
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
3713
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2913
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.