RE: Policy-Based Design/Templates/Quantlib
Posted by Luigi Ballabio-2 on
URL: http://quantlib.414.s1.nabble.com/Policy-Based-Design-Templates-Quantlib-tp2601p2606.html
Hi all,
sorry, I don't have much time for answering at lenght---it will
have to wait a few days. However:
At 09:14 AM 7/14/03 -0400, Lou, Wujiang wrote:
>This kind of template design for pricer (see after ==>) is less preferred
>in a trading system because in cases where multiple models are available
>for the same instrument, the trading system typically allows users to
>configure their model choice and let them switch around. This dynamic
>behavior vs the static polymorphism nature of template is mind twisting.
run-time polymorphism is not prevented by the current design. In general,
compile-time and run-time polymorphism do not exclude each other--they can
be mixed, as in:
class Model {
public:
virtual void foo() = 0;
};
class SomeInstrument {
public:
double calculate(Model* m);
};
template <class Policy1, class Policy2=SomeDefault>
class Foo : public Model {
public:
void foo() { /* whatever, using the chosen policies */ }
};
Model* modelFactory(int tag) {
switch (tag) {
case 1:
return new Foo<SomePolicy>;
case 2:
return new Foo<SomeOtherPolicy>;
case 3:
return new Foo<SomeOtherPolicy,NotTheDefault>;
default:
return NULL;
}
}
int main() {
std::cout << "Choose a model:" << std::endl;
std::cout << "[1]: vanilla-flavored" << std::endl;
std::cout << "[2]: peppermint-flavored" << std::endl;
std::cout << "[3]: caffeinated" << std::endl;
Model* model;
int tag;
std::cin >> tag;
model = modelFactory(tag);
while (model == NULL) {
std::cout << "Wrong choice, try again" << std::endl;
std::cin >> tag;
model = modelFactory(tag);
}
SomeInstrument i;
std::cout << "Your result is " << i.calculate(model) << std::endl;
delete model;
return 0;
}
et voila', run-time polymorphism! (of course in a real trading system the
factory would be called behind a configuration window with checkboxes and
stuff, and it would be passed more arguments based on which the correct
model is to be chosen.)
Later,
Luigi
P.S. Also, you can easily turn compile-time polymorphism into run-time
polymorphism by means of a polymorphic proxy class, but you can't do the
opposite...