473,416 Members | 1,566 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,416 software developers and data experts.

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(Instrument* ptrSuccessor) : m_ptrSuccessor(ptrSuccessor)
{ }
template<typename 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 ConcreteInstrument : public Instrument
{
public:
template<typename 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
// ConcreteInstrument, so then
ConcreteInstument will be a class template.
};

template<typename 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 ConcreteInstrument 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 10260

"Sebastian Faust" <sf*************@logic-software.de> wrote in message
news:bn*************@ID-55442.news.uni-berlin.de...
class ConcreteInstrument : public Instrument
{
public:
template<typename 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
// ConcreteInstrument, so then
ConcreteInstument 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 (InstrumentCommand& op) {visit
(static_cast<Command&>(op);}
virtual void visit (AnotherCommand& op) {visit
(static_cast<Command&>(op);}
virtual void visit (YetAnotherCommand& op) {visit
(static_cast<Command&>(op);}
};

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

class InstrumentCommandVisitor : public CommandVisitor
{
public:
void visit (InstrumentCommand& 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_instrument" member of Command, which does not
take or return anything relying on the template parameter.

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

template<typename 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_instrument" member of Command, which does not
take or return anything relying on the template parameter.

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

template<typename 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<Command&> (c));}
virtual void visit (CommandDouble& c) {visit (static_cast<Command&>
(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_Patterns_ 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
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...
6
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...
6
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...
11
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...
14
by: v4vijayakumar | last post by:
Why we need "virtual private member functions"? Why it is not an (compile time) error?
5
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...
2
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...
2
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...
5
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
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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,...
0
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...
0
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...
0
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,...
0
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...

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.