I disagree with one answer above, which states that a template-based solution can have worse costs or lead time. In fact, solutions based on templates allow you to write code faster, eliminating the need for virtual functions or by pointer (I agree, however, that using this mechanism still does not impose significant overhead.)
Suppose that you are customizing your processing interface using a series of “attributes”, that is, you are processing parts or functions that can be configured by the client to configure the processing interface. Imagine a class with three (to see an example) processing parameterizations:
template <typename Proc1, Proc2 = do_nothing, Proc3 = do_nothing> struct ProcessingInterface { static void process(mpz_class& element) { Proc1::process(element); Proc2::process(element); Proc3::process(element); } };
If the client has different "processors" with a static function "process" that know how to process an element, you can write a class to "combine" these three processes. Note that the do_nothing class has an empty method by default:
class do_nothing { public: static void process(mpz_class&) {} };
These calls have no overhead. These are ordinary calls, and the client can configure processing using ProcessingInterface<Facet1, Facet2>::process(data); .
This only applies if you know different “faces” or “processors” at compile time, which is similar to your first example.
Note that you can write a more complex class using metaprogramming tools like boost.mpl library to include more classes, iterate through them, etc.
source share