Neelesh Bodas wrote:
qn*****@hotmail.com wrote:
In an attempt to use templates, what I did was:
----- ClassA.h --------------------
class A
{
public:
template <class S> void send(S);
This means that send is a template function. In the current context, S
could be Message1, Message2 etc.
I would like to find out how to implement the above using templates.
template <class S> void send(S msg)
{
// write your code as usual here, and use S wherever you used
Message1 etc in your original code. (There are some more issues but
they could be pointed out if the code is made available.)
}
Hope this helps.
Depending on your design, you might prefer to use the dynamic
polymorphism of inheritance rather than the static polymorphism of
templates. In particular, you could send messages by a base class with
a standard interface, e.g.,
struct Msg
{
virtual std::string Get() const = 0;
};
struct Msg1 : Msg
{
void Set( /* ... */ ) { /*...*/ }
std::string Get() const { /* ... */ }
};
struct Msg2 : Msg
{
void Set( /* ... */ ) { /*...*/ }
std::string Get() const { /* ... */ }
};
struct A
{
void Send( const Msg& msg )
{
std::cout << msg.Get() << std::endl;
}
};
struct B
{
template<class M>
void Send( const M& msg )
{
std::cout << msg.Get() << std::endl;
}
};
void Foo()
{
Msg1 m1;
Msg2 m2;
m1.Set( /*...*/ );
m2.Set( /*...*/ );
A a;
a.Send( m1 );
a.Send( m2 );
B b;
b.Send( m1 );
b.Send( m2 );
}
Class A implements dynamic polymorphism and class B static polymorphism
(technically, the inheritance specs on Msg1 and Msg2 should be deleted
for static polymorphism, but you get the idea). A tends to be more
efficient in terms of code size, especially if there are many Msg
classes, and B tends to be *slightly* more efficient in terms of
execution speed. I would prefer the first way (class A) if possible.
Cheers! --M