Basically, you have 3 options. You have to decide yourself, which is the appropriate in your situation:
1) if classes X and Y are under your control: why not make them related by inheritance (perhaps a common base class)?
2) provide two separate implementations for the two cases
X * m_x; // init to NULL somewhere
Y * m_y;
bool Z::check_config( ) {
if (result_of_database == 0)
m_x = new X;
else
m_y = new Y;
return true;
}
void Z::other_method( ) {
if (m_x) m_x->lassNumber();
if (m_y) m_y->lastNumber();
pointer->lastNumber( );
}
X * m_x; // init to NULL somewhere
Y * m_y;
bool Z::check_config( ) {
if (result_of_database == 0)
m_x = new X;
else
m_y = new Y;
return true;
}
void Z::other_method( ) {
if (m_x) m_x->lassNumber();
if (m_y) m_y->lastNumber();
pointer->lastNumber( );
}
To copy to clipboard, switch view to plain text mode
3) templates
Note that that this is very similar to 2), just that the template saves you the work of having to write to separate other_methods, the compiler generates those for you.
However, as soon as you want to do something for X that is not possible in Y, you have to code that in other_method. The template method is just a way to write code once for syntactically identically useable objects.
void other_method()
{
if (m_x) do_other_method(m_x);
if (m_y) do_other_method(m_y);
}
template<typename Config>
void Z::do_other_method(Config *cfg) {
cfg->lassNumber();
}
void other_method()
{
if (m_x) do_other_method(m_x);
if (m_y) do_other_method(m_y);
}
template<typename Config>
void Z::do_other_method(Config *cfg) {
cfg->lassNumber();
}
To copy to clipboard, switch view to plain text mode
All code untried, but I hope the idea is understandable.
HTH
Bookmarks