473,725 Members | 2,212 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

virtual function template - design probelm

Hi,

I have a design problem about which I am thinking now for a while and still
couldnt find any help in deja. What I need is something like a virtual
function template. I know that this is not possible, so I need "something
like" a virtual function template. I read in some threads that there is a
workaround using the visitor pattern. I read therefore in the book "Modern
c++ Design" about this pattern, but couldnt find any help to my approach. So
now to my problem:

class Instrument
{
public:
Instrument(Inst rument* ptrSuccessor) : m_ptrSuccessor( ptrSuccessor)
{ }
template<typena me Command> // I know this is not
possible, but that's what I wanna do
void virtual handle_command( Command& op) = 0;
protected:
Instrument* m_ptrSuccessor;
};

class ConcreteInstrum ent : public Instrument
{
public:
template<typena me Command> // I know this is not
possible, but that's what I wanna do
void virtual handle_command( Command& op)
{
if(op->is_instrument( ))
{
_state = op->get_state();
}
else
m_ptrSuccessor->handle_command (op);
}
protected:
int _state; // this could be any other type, maybe the type
will later be defined in form of a template parameter of the class
// ConcreteInstrum ent, so then
ConcreteInstume nt will be a class template.
};

template<typena me Type, Type TYPE>
class Command
{
public:
Command(Type& state) : _state(state) { };
public:
virtual bool is_instrument()
{
if(_state == TYPE)
return true;
else
return false;
}
virtual Type get_state() { return _state; }
protected:
Type _state;
};

Usually in Command._state there is some kind of raw data which includes
type-info, and the real state. In the ConcreteInstrum ent we then only need
the real state-data, so usually the get_state and is_instrument function
will perform some extracting processing to extract the needed data out of
the raw-data.

For any help on my problem thanks in advance,
Sebastian
Jul 19 '05 #1
9 10280

"Sebastian Faust" <sf************ *@logic-software.de> wrote in message
news:bn******** *****@ID-55442.news.uni-berlin.de...
class ConcreteInstrum ent : public Instrument
{
public:
template<typena me Command> // I know this is not
possible, but that's what I wanna do
void virtual handle_command( Command& op)
{
if(op->is_instrument( ))
{
_state = op->get_state();
}
else
m_ptrSuccessor->handle_command (op);
}
protected:
int _state; // this could be any other type, maybe the type
will later be defined in form of a template parameter of the class
// ConcreteInstrum ent, so then
ConcreteInstume nt will be a class template.
};


I'm not sure exactly what you're shooting for, but it does look from your
example like the visitor pattern may help. Here's the basic idea:

// base class for all commands
class Command
{
public:
// this line MUST be reimplemented in every command type, even though it
looks the same.
virtual void accept (CommandVisitor & visitor) {visitor.visit (*this);}
};

// base class for all visitors
class CommandVisitor
{
public:
virtual void visit (Command& op) {}
virtual void visit (InstrumentComm and& op) {visit
(static_cast<Co mmand&>(op);}
virtual void visit (AnotherCommand & op) {visit
(static_cast<Co mmand&>(op);}
virtual void visit (YetAnotherComm and& op) {visit
(static_cast<Co mmand&>(op);}
};

OK, now we want something that does one thing for InstrumentComma nd's and
another for any other command type. So, all we need to write is this:

class InstrumentComma ndVisitor : public CommandVisitor
{
public:
void visit (InstrumentComm and& op) {_state = op->get_state(); }
void visit (Command& op)
{m_ptrSuccessor->handle_command (op);}
};

Now, in order to use this system, we say something like:

Command& command = getCommand();
command.accept (visitor);

Now, the actual type of the command will determine which of visitor's
overloaded visit functions will get called. Note that the functions for the
CommandVisitor let you override for just the Command types you are
interested in, and not worry about the rest.

The biggest problem with this is you will need to add a function to
CommandVisitor every time you add a new Command type. Depending on your
needs, an RTTI visitor may be more appropriate.

I hope this made sense and/or helped.

Jul 19 '05 #2
Hi,
class Command
{
public:
// this line MUST be reimplemented in every command type, even though it looks the same.
virtual void accept (CommandVisitor & visitor) {visitor.visit (*this);}
};

The problem here is that the Command is a class template. So with different
template parameters I always get a new type. Now if I wanna give an object
of this type to the visit function as you did then there is no type Command,
there are only different Types like:
Command<int, 3>
Command<float, 7.0>
and so on. So the problem is that I can't give to the virtual function visit
a from Command derived class Object, cause there is no Command-Class.

That's why in my opinion I have to simulate something like virtual function
templates, cause than I can give the different Command-Types to that
virtual-function of the Instrument-Class and cause the function
handle_command is virtual always the right handle_command-function of the
right Instrument-Class will be called.

If you need any further information just ask again.

Thanks in advance
Sebastian
Jul 19 '05 #3

"Sebastian Faust" <sf************ *@logic-software.de> wrote in message
news:bn******** *****@ID-55442.news.uni-berlin.de...> The problem here is
that the Command is a class template. So with different
template parameters I always get a new type. Now if I wanna give an object
of this type to the visit function as you did then there is no type Command, there are only different Types like:
Command<int, 3>
Command<float, 7.0>
Are floats allowed as template parameters? I think that's nonstandard.
and so on. So the problem is that I can't give to the virtual function visit a from Command derived class Object, cause there is no Command-Class.


How about just making a Command class, then? It looks like in that function
you are only using the "is_instrum ent" member of Command, which does not
take or return anything relying on the template parameter.

class Command
{
public:
virtual bool is_instrument() =0;
};

template<typena me Type, Type TYPE>
class CommandImpl : public Command
{
// ...
};

This looks like it does what you want.

Jul 19 '05 #4
Hi,

How about just making a Command class, then? It looks like in that function you are only using the "is_instrum ent" member of Command, which does not
take or return anything relying on the template parameter.

class Command
{
public:
virtual bool is_instrument() =0;
};

template<typena me Type, Type TYPE>
class CommandImpl : public Command
{
// ...
};

This looks like it does what you want.


Yes that's what I want to do, but the problem is that Command has to be a
class template, cause the the get_state() function has different
return-types in dependency of the Type set by the template definition. So I
still have the problem that I have to call a virtual member function (
handle_command ) of the instrument class with different types. Therefore I
would need "something like virtual function templates". But I still couldnt
figure out how to work around this. And that's what I am searching for.

If you have any further questions.... cause my english is not that perfect,
then just ask me.

Thanks in advance
Sebastian
Jul 19 '05 #5

"Sebastian Faust" <sf************ *@logic-software.de> wrote in message
news:bn******** *****@ID-55442.news.uni-berlin.de...
handle_command ) of the instrument class with different types. Therefore I
would need "something like virtual function templates". But I still couldnt figure out how to work around this. And that's what I am searching for.
I don't know of anything that works like virtual function templates, and I
expect if there was such a thing, it would be troublesome enough to dominate
your entire program. It is more likely you should put other design elements
on the table.
If you have any further questions.... cause my english is not that perfect, then just ask me.


I think it will be very hard to give you any advice without knowing what the
purpose of your design is. So, you claim Command must be a template class.
Why did you choose a template class for Command? For how many different
types would it be reasonable to instantiate Command? What is a "Command"
and what does it need to do?

I'm especially worried about your Command template because you gave an
example of Command <float, 1.0>, which is questionable practice even were it
standard. Now, the compiler may or may not let Command <float, 1.00000000>
and Command <float, 1.00000001> be the same type. The second parameter
should probably be a constant member instead.

If all Commands are of numeric types, why not just use a double?
Instantiating for different types might confuse the design issues.

Also, you have stated that handle_command must be virtual. Why? What does
it do? "Handle_command " is so general it sounds like you are avoiding
making design decisions about things that can be done with commands - why is
this necessary? What is an "Instrument "?

Hope we can figure something out.
Kevin

Jul 19 '05 #6
Hi,
I don't know of anything that works like virtual function templates, and I
expect if there was such a thing, it would be troublesome enough to dominate your entire program. It is more likely you should put other design elements on the table. ok... from Stephen Love I got the following link which implements "something
like virtual function templates":
http://www.slove.pwp.blueyonder.co.u...of_idioms.html
But sadly at the moment I dont know how to use it in my case.
I think it will be very hard to give you any advice without knowing what the purpose of your design is. So, you claim Command must be a template class. Why did you choose a template class for Command? For how many different
types would it be reasonable to instantiate Command? What is a "Command"
and what does it need to do? So my basic problem is that I wanna implement the chain of responsibility
pattern. In my case the Instruments are the elments of the chain. Now I have
something lika a processor which creates Command-Objects. These Command
objects should be handled by the Instruments handle_command function. If one
Instrument "think" it is responsible for that command it will process it
further. Otherwise it will call the handle_command function of the
successor. For me it would be much better when the Command-class would be a
class template, cause the types used in the Command are supposed to be
different. What I mean with that is, that is could be possible that there
will be Commands with other data-types in it, and that's the problem why I
think I need something like virtual function templates.
I'm especially worried about your Command template because you gave an
example of Command <float, 1.0>, which is questionable practice even were it standard. Now, the compiler may or may not let Command <float, 1.00000000> and Command <float, 1.00000001> be the same type. The second parameter
should probably be a constant member instead. Why the Compiler may or may not let Command <float, 1.00000000>
and Command <float, 1.00000001> be the same type?

If all Commands are of numeric types, why not just use a double?
Instantiating for different types might confuse the design issues. No some commands will use for example unsigned char, others strings, and so
on.
Also, you have stated that handle_command must be virtual. Why? What does it do? "Handle_command " is so general it sounds like you are avoiding
making design decisions about things that can be done with commands - why is this necessary? What is an "Instrument "? The handle_command function will process the data, which is in the Command,
but only if it thinks that it is responsible for that Command, otherwise it
will send it to the next instrument. An Instrument could for example be a
speed-instrument, which measures the speed of a car. Always when the speed
of the car change, the processor will send a Speed-Command which then has to
be processed by the correct instrument.
The whole thing is not that easy, so the fact that there is a chain of
responisbility and a processor makes sense ( at least for me ), cause all
instrument are connected to a serial bus. So they send there data on that
serial bus one after another to a queue, where the processor then goes and
reads the next record to transform it to a command and send it to the chain.
I hope that makes things a bit more clear.
Hope we can figure something out.

That would be really cool.

Bye and thanks,
Sebastian
Jul 19 '05 #7
"Sebastian Faust" <sf************ *@logic-software.de> wrote in message
news:bn******** *****@ID-55442.news.uni-berlin.de...> So my basic problem is
that I wanna implement the chain of responsibility
pattern. In my case the Instruments are the elments of the chain. Now I have something lika a processor which creates Command-Objects. These Command
objects should be handled by the Instruments handle_command function. If one Instrument "think" it is responsible for that command it will process it
further. Otherwise it will call the handle_command function of the
successor. For me it would be much better when the Command-class would be a class template, cause the types used in the Command are supposed to be
different. What I mean with that is, that is could be possible that there
will be Commands with other data-types in it, and that's the problem why I
think I need something like virtual function templates.
This definitely sounds like a job for the visitor pattern. See my first
reply for how to implement it. Basically, you should have a base Command
class, and derive classes of that with whatever data is appropriate. Say
you have a FloatCommand object, then if the visitor implements visit
(FloatCommand&) it can access specific member functions of the FloatCommand
class, and is not limited to the capabilities of the base Command class.

You should use templates when the class or function should work for any
class which meets certain assumptions. However, if the number of
possibilities is finite, polymorphism is better since the subclasses can
vary independently.
Why the Compiler may or may not let Command <float, 1.00000000>
and Command <float, 1.00000001> be the same type?
The precision of floats and doubles is implementation-defined; so, on some
implementations 1.00000000 == 1.00000001 and on others 1.00000000 !=
1.00000001.
The handle_command function will process the data, which is in the Command, but only if it thinks that it is responsible for that Command, otherwise it will send it to the next instrument. An Instrument could for example be a
speed-instrument, which measures the speed of a car. Always when the speed
of the car change, the processor will send a Speed-Command which then has to be processed by the correct instrument.


This sounds like a good application of the visitor pattern; why do you think
it won't work?


Jul 19 '05 #8
Hi,

This definitely sounds like a job for the visitor pattern. See my first
reply for how to implement it. Basically, you should have a base Command
class, and derive classes of that with whatever data is appropriate. Say
you have a FloatCommand object, then if the visitor implements visit
(FloatCommand&) it can access specific member functions of the FloatCommand class, and is not limited to the capabilities of the base Command class.

Yes I thought about the Visitor pattern too, but I don't know exactly how to
apply it in my case. I think the visited-object is the Instrument and the
Visitor is the Command, or am I wrong? But how can I handle the different
return types in the Command class?

Thanks in advance
Sebastian
Jul 19 '05 #9

"Sebastian Faust" <sf************ *@logic-software.de> wrote in message
news:bn******** *****@ID-55442.news.uni-berlin.de...
Yes I thought about the Visitor pattern too, but I don't know exactly how to apply it in my case. I think the visited-object is the Instrument and the
Visitor is the Command, or am I wrong? But how can I handle the different
return types in the Command class?


You have it backwords. Since the Instrument acts on the Command, the
Instrument will be the visitor. So you can have:

class Command;
class CommandInt;
class CommandDouble;

class Instrument
{
public:
virtual void visit (Command&) {}
virtual void visit (CommandInt& c) {visit (static_cast<Co mmand&> (c));}
virtual void visit (CommandDouble& c) {visit (static_cast<Co mmand&>
(c));}
virtual ~Instrument() {}
};

class Command
{
public:
virtual void accept (Instrument& v) =0;
virtual ~Command() {}
};

class CommandInt
{
public:
void accept (Instrument& v) {v.visit (*this);}
int getInt() {return 5;}
};

class CommandDouble
{
public:
void accept (Instrument& v) {v.visit (*this);}
double getDouble() {return 3.14159;}
};
class MyInstrument : public Instrument
{
public:
void visit (Command&) {std::cout << "Visited unknown command" <<
std::endl;}
void visit (CommandInt& c) {
std::cout << "Visited int command with value: " << c.getInt() <<
std::endl;
}

void visit (CommandInt& c) {
std::cout << "Visited double command with value: " << c.getDouble()
<< std::endl;
}
};

int main()
{
Command *ci = new CommandInt;
Command *cd = new CommandDouble;

MyInstrument v;

ci-> accept (v);
cd-> accept (v);

delete ci;
delete cd;
};

As you can see, the visitor sees the actual type of the command. This is
the point of the pattern. Please see _Design_Pattern s_ or search for
"visitor pattern" if you need more info.


Jul 19 '05 #10

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

Similar topics

25
5416
by: Stijn Oude Brunink | last post by:
Hello, I have the following trade off to make: A base class with 2 virtual functions would be realy helpfull for the problem I'm working on. Still though the functions that my program will use a lot are the ones that are virtual and thus will slow down the calculation, at least that is what what I have read on several places on the internet. It makes sense the program has to work with some kind off lookup table for the virtual...
6
4004
by: RainBow | last post by:
Greetings!! I introduced the so-called "thin-template" pattern for controlling the code bloat caused due to template usage. However, one of the functions in the template happens to be virtual as well. To support thin-template, I need to make virtual function as inline. Now, I know that compiler would generate an out-of-line copy when it
6
1805
by: Amadeus W. M. | last post by:
Sometimes - more often than I would like - I run into situations where I need a member function to be simultaneously templated and virtual. I know it can be done, but I'm wondering if there's some clever design trick that can circumvent this problem. Example: template <class Pixel_t> class Image;
11
3434
by: Nindi73 | last post by:
A few days a ago I posted my code for a deep copy pointer which doesn't require the pointee object to have a virtual copy constructor. I need help with checking that it was exception safe and exception neutral/ I got a reply from Bux with his code for a smart pointer with far fewer lines of code and more cleaner design, not over engineered like mine. ...
14
4209
by: v4vijayakumar | last post by:
Why we need "virtual private member functions"? Why it is not an (compile time) error?
5
3161
by: alind | last post by:
I m having a problem with templates. A per C++ std says i cant use override template virtual functions. in other words virtual functions cant be templates due to some vtable size issues. Now i want to simulate it somehow. I read in some other posts that it is somehow possible throg visitor pattern but i m unable to get it done. My intended code is posted below. can somebody give me a workaround to get this functionality.Any help is appreciated....
2
3694
by: Markus Dehmann | last post by:
I have an abstract base class called Data. It has a pure virtual function virtual void write(std::ostream& out) =0; which writes the internal data to a stream. Now the problem is that this is not appropriate for some implementations of the class. Some implementations have an internal representation that they should rather write into several separate files. So for those, something like this would be more appropriate:
2
2412
by: cmonthenet | last post by:
Hello, I searched for an answer to my question and found similar posts, but none that quite addressed the issue I am trying to resolve. Essentially, it seems like I need something like a virtual static function (which I know is illegal), but, is there a way to provide something similar? The class that is the target of my inquiry is a template class that interfaces to one of several derived classes through a pointer to a base class. The...
5
2952
by: want.to.be.professer | last post by:
For OO design, I like using virtual member function.But considering efficiency, template is better. Look at this program, class Animal { public: virtual void Walk() = 0; }; class Dog
0
8752
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
9257
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
9113
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...
1
6702
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4519
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
4784
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3221
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
2635
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2157
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.