Suppose one is writing a library behavior the classes A1, A2 and A3, which
share some common behavior. Some applications will only use one of the
classes, while other applications will use all of them.
Because the classes share common behavior, the library designed has to
choose wether to introduce an abstract base class A, or not. Introducing an
ABC has the advantage of run time flexibility, but efficiency suffers
(virtual functions & inlining, ...).
To have the best of both worlds, you could try this:
class A1 // no inheritance
{
// no virtuals
f();
};
class A2
{
f();
};
class A3
{
f();
};
class A
{
virtual f();
};
template <class Ax>
class A_wrapper : public A
{
public:
A_wrapper(Ax& a) : a_(a) {}
f() { return a_.f(); }
private:
Ax a_;
}
Applications that use only one of the classes:
A2 a2;
a2.f();
Applications that need run time flexibility:
A * a = new A_wrapper<A2>(A2());
What do you think of this library design technique ?
Note that this technique could be applied to e.g. the random number facility
that was proposed to the standard.
Most applications will choose one random number generator and use it, e.g.
mersenne_twister or linear_congruential.
However, some applications will (for example) want to study the effect the
random number generator has on their simulation. For these applications,
run time flexibility is important.
Run time flexibility can be accomplished by introducing the base class
uniform_random_number_generator, and the class
uniform_random_number_generator_wrapper<T>. Note that
uniform_random_number_generator already exists, as a concept (table 5.1),
and the uniform_random_number_generator_wrapper<T> class is very simple,
just because all existing classes already are implemented according to the
uniform_random_number_generator concept. And even if a class had a slightly
different interface, the problem could be solved using an explicit
specialization of the uniform_random_number_generator_wrapper class
template.
So again, what do you think of this library design technique ?
best regards,
Ares Lagae