473,549 Members | 2,761 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

generic programming and dynamic polymorphism


Cracow, 20.10.2004

Hello,

As far as I understand, the generic programming basically consists
in using templates for achieving a static polymorphism of the
various code fragments, and their reuse for various template
parameters. I wonder if there exist techniques for achieving
a dynamic polymorphism using the generic programming. Is this
possible? If yes, can anyone show me simple examples in C++
of how this can be done?

Sincerely,

L.B.
*-------------------------------------------------------------------*
| Dr. Leslaw Bieniasz, |
| Institute of Physical Chemistry of the Polish Academy of Sciences,|
| Department of Electrochemical Oxidation of Gaseous Fuels, |
| ul. Zagrody 13, 30-318 Cracow, Poland. |
| tel./fax: +48 (12) 266-03-41 |
| E-mail: nb******@cyf-kr.edu.pl |
*-------------------------------------------------------------------*
| Interested in Computational Electrochemistr y? |
| Visit my web site: http://www.cyf-kr.edu.pl/~nbbienia |
*-------------------------------------------------------------------*
Jul 22 '05 #1
4 4413
Leslaw Bieniasz wrote:
Cracow, 20.10.2004

Hello,

As far as I understand, the generic programming basically consists
in using templates for achieving a static polymorphism of the
various code fragments, and their reuse for various template
parameters. I wonder if there exist techniques for achieving
a dynamic polymorphism using the generic programming. Is this
possible? If yes, can anyone show me simple examples in C++
of how this can be done?


It all depends on how narrowly you define "generic programming". Do you
restrict it to compile-time constructs like templates, or do you broaden
the definition to encompass other methods of maintaining a consistent
interface across many different actual types.

Virtual functions are the standard way of implementing dynamic
polymorphism, but templates can indeed be a big help. Consider the
example of a "callback" template.

class adapter_base{
public:
virtual ~adapter_base() {}
virtual void operator()() = 0;
};

template<typena me T>
class adapter: public adapter_base{
T& object;
public:
explicit adapter(T& t): object(t){}
virtual void operator()(){ object(); }
};
class callback_execut er{
std::vector<ada pter_base*> callbacks;
public:
template<typena me T>
void add_callback(co nst T& t){
callbacks.push_ back(new adapter(t));
}
void execute_all(){
for (std::vector<ad apter_base*>::i terator i = callbacks.begin ();
i != callbacks.end() ;
++i)
{
(*(*i))();
}
}
~callback_execu ter(){
for (std::vector<ad apter_base*>::i terator i = callbacks.begin ();
i != callbacks.end() ;
++i)
{
delete *i;
}
}
};
struct callback_A{
void operator()(){
std::cout << "callback A executed!\n";
}
};

struct callback_B{
void operator()(){
std::cout << "callback B executed!\n";
}
};

int main(){
callback_execut er c;
c.add_callback( callback_A());
c.add_callback( callback_B());
c.execute_all() ;
}
Regards,
Jacques.
Jul 22 '05 #2
Jacques Labuschagne wrote:
Leslaw Bieniasz wrote:
Cracow, 20.10.2004

Hello,

As far as I understand, the generic programming basically consists
in using templates for achieving a static polymorphism of the
various code fragments, and their reuse for various template
parameters. I wonder if there exist techniques for achieving
a dynamic polymorphism using the generic programming. Is this
possible? If yes, can anyone show me simple examples in C++
of how this can be done?

It all depends on how narrowly you define "generic programming". Do you
restrict it to compile-time constructs like templates, or do you broaden
the definition to encompass other methods of maintaining a consistent
interface across many different actual types.

Virtual functions are the standard way of implementing dynamic
polymorphism, but templates can indeed be a big help. Consider the
example of a "callback" template.


I've made some corrections below, which do not diminish the value of
the example, only fix some bugs to make it compilable.

class adapter_base{
public:
virtual ~adapter_base() {}
virtual void operator()() = 0;
};

template<typena me T>
class adapter: public adapter_base{
T& object;
public:
explicit adapter(T& t): object(t){}
virtual void operator()(){ object(); }
};


#include <vector>
class callback_execut er{
std::vector<ada pter_base*> callbacks;
public:
template<typena me T>
void add_callback(co nst T& t){
void add_callback(T& t) {
callbacks.push_ back(new adapter(t));
callbacks.push_ back(new adapter<T>(t));
}
void execute_all(){
for (std::vector<ad apter_base*>::i terator i = callbacks.begin ();
i != callbacks.end() ;
++i)
{
(*(*i))();
}
}
~callback_execu ter(){
for (std::vector<ad apter_base*>::i terator i = callbacks.begin ();
i != callbacks.end() ;
++i)
{
delete *i;
}
}
};

#include <iostream>

struct callback_A{
void operator()(){
std::cout << "callback A executed!\n";
}
};

struct callback_B{
void operator()(){
std::cout << "callback B executed!\n";
}
};

int main(){
callback_execut er c;
c.add_callback( callback_A());
c.add_callback( callback_B());
Can't use temporaries. Have to declare real objects.

callback_A a;
c.add_callback( a);
callback_B b;
c.add_callback( b);

Otherwise, the code has to be severely const-corrected.
c.execute_all() ;
}


V
Jul 22 '05 #3
Victor Bazarov wrote:
I've made some corrections below, which do not diminish the value of
the example, only fix some bugs to make it compilable.


Thanks. :-)
Jacques.
Jul 22 '05 #4

Cracow, 21.10.2004

Hello,

On Wed, 20 Oct 2004, Jacques Labuschagne wrote:
As far as I understand, the generic programming basically consists
in using templates for achieving a static polymorphism of the
various code fragments, and their reuse for various template
parameters. I wonder if there exist techniques for achieving
a dynamic polymorphism using the generic programming. Is this
possible? If yes, can anyone show me simple examples in C++
of how this can be done?


It all depends on how narrowly you define "generic programming". Do you
restrict it to compile-time constructs like templates, or do you broaden
the definition to encompass other methods of maintaining a consistent
interface across many different actual types.

Virtual functions are the standard way of implementing dynamic
polymorphism, but templates can indeed be a big help. Consider the
example of a "callback" template.

What I have in mind is whether one can avoid using virtual functions,
but achieve the same effect of dynamic polymorphism using only templates.
The virtual functions allow one to differentiate the behaviour of objects
depending on the dynamic, run-time type of the object. However, in
principle the types of all objects created within a program are always
exactly known at the moment of their creation. Therefore, one might
expect (at least theoretically) that if this static, compile-time type
information could be passed somehow to the code that calls the object
methods, then one could avoid using the virtual functions, but obtain
the same polymorphic behaviour. This might be pretty complicated to
do, I suppose.

My question is motivated by my attempts to understand some
existing libraries, like the matrix algebra library MTL, which
is said to use generic programming and templates. Various types
of vectors/matrices are there defined as templates, each one for
one matrix/vector type, and dynamic polymorphism is avoided (I may
be wrong though). Therefore, there does not seem to be anything
like a base matrix or vector class, from which all types are derived.
I therefore do not see a way to write polymorphic constructs
such as for example

Add(a,b,c)

which could perform addition c = a+b

of various types of vectors or matrices, assuming that a,b and c
are pointers or references to the base type. Instead, one always
have to specify to which particular types the a, b and c point/refer
to, whenever a,b and c are declared. This appears a severe limitation
to me, because various parts of the code must always be specialised,
or occur as templates with many parameters (representing, for example the
types of a, b, and c in the above example). Therefore, I am asking if
there exist techniques that would allow me to achieve dynamic polymorphism
without using class hierarchies with virtual functions.

L.B.
*-------------------------------------------------------------------*
| Dr. Leslaw Bieniasz, |
| Institute of Physical Chemistry of the Polish Academy of Sciences,|
| Department of Electrochemical Oxidation of Gaseous Fuels, |
| ul. Zagrody 13, 30-318 Cracow, Poland. |
| tel./fax: +48 (12) 266-03-41 |
| E-mail: nb******@cyf-kr.edu.pl |
*-------------------------------------------------------------------*
| Interested in Computational Electrochemistr y? |
| Visit my web site: http://www.cyf-kr.edu.pl/~nbbienia |
*-------------------------------------------------------------------*
Jul 22 '05 #5

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

Similar topics

18
12564
by: Ken | last post by:
Hi. Can anyone refer me to any articles about the compatibility between c++ polymorphism and real-time programming? I'm currently on a real-time c++ project, and we're having a discussion about whether we should allow polymorphism. Our system is not embedded and does not need to be as real-time as, say, a pacemaker. But it does involve...
65
4208
by: Roger Smythe | last post by:
A means for the progressive decomposition a problem space into increasingly simpler component parts such that these component parts represent higher levels of conceptual abstraction, and are completely independent of each other except for their well-defined interfaces. This was an attempt to explain the gist of OOP to programmers accustomed...
15
3024
by: rwf_20 | last post by:
I just wanted to throw this up here in case anyone smarter than me has a suggestion/workaround: Problem: I have a classic producer/consumer system which accepts 'commands' from a socket and 'executes' them. Obviously, each different command (there are ~20 currently) has its own needed functionality. The dream goal here would be to...
13
14597
by: Krivenok Dmitry | last post by:
Hello all! Perhaps the most important feature of dynamic polymorphism is ability to handle heterogeneous collections of objects. ("C++ Templates: The Complete Guide" by David Vandevoorde and Nicolai M. Josuttis. Chapter 14.) How to implement analogue of this technique via static polymorphism? Perhaps there is special design pattern for...
25
3004
by: Lars | last post by:
Hi, I have a base class holding a generic list that needs to be accessed by both the base class and its subclasses. What is the best solution to this? I am fairly new to generics, but I am aware of that fact that if you have a class B, that inherits from A, then List<Bdoes NOT inherit from List<A>. So I understand why the example below...
9
2119
by: Royt | last post by:
Maybe it's a stupid question, but I really couldn't figure it out. C++ is expected to be a better C, provides compatibility with C, and is able to do all that C can do. however, the number of projects in sf.net written by C++ is always smaller than that of C, many people directly turn to Java or C# after they learned C. Now that C++ is a...
9
5833
by: Steve Richter | last post by:
in a generic class, can I code the class so that I can call a static method of the generic class T? In the ConvertFrom method of the generic TypeConvert class I want to write, I have a call to the static Parse method of the conversion class. if (InValue is string) return T.Parse((string)InValue); else return base.ConvertFrom(context,...
3
3816
by: Johs | last post by:
I have read that when you are using templates you are making generic programs. But I don't see whats so generic about templates. You can make generic programs without templates through the use of function overload and the virtual functionality. As I understand when you use templates you just increase the runtime performance since the code...
11
1494
by: Vitor | last post by:
I have been writing some large programs and games lately and I have had people advise me that I need to write more object oriented programs. I also I understand the concept and have written some small programs to understand the theory. class unit{ protected: int locx; int locy;
0
7477
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...
0
7750
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. ...
0
7838
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...
0
6084
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...
1
5396
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...
0
3503
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1971
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
1
1084
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
790
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...

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.