template based design

M

mjm

Folks,

I am encountering the following problem when using templates in
writing a library:
since template functions are only instantiated at the point of use
classes don't have to follow well defined interfaces anymore. When the
template is instantiated the compiler looks for all the pieces and if
it finds them all you have your function and if not you have a
compiler error.

I'll try to make this more concrete in the following example: I am
writing a library for option pricing. There are two approaches:

1. Monte Carlo simulation.

For this I need price paths and the option must define a method

Double payoffAlongCurrentPath(PathGenerator*);


2. Tree methods.

For this to work the option must define a method

Double payoffAtCurrentNode(Tree*);


Now I can go ahead and define standalone functions

namespace Pricing {

template<class PathGenerator, class Option>
Double monteCarloPrice(PathGenerator* thePathGenerator, Option*
theOption)
{
// generate some paths and process them....
Double h=theOption->payoffclassAlongCurrentPath(thePathGenerator);
//...............
}


template<class Tree*, class Option>
Double treePrice(Tree* theTree, Option* theOption)
{
// process the nodes in the tree...
Double h=theOption->payoffAtCurrentNode(theTree);
//...............
}

};



Now the class Option needs to implement neither of the two methods 1.
or 2.
If 1. is not implemented all that happens is that Monte Carlo pricing
won't work
and if 2. is not implemented treePricing won't work.

For some options there are no trees and for others there are no paths
so we can't have a uniform interface for the class Option.

If I provide such functions how is the user supposed to know which
methods the class Option has to implement in order to get certain
functionality.
I would have to define the class Option with trivial implementations
of 1. and 2. (maybe an error message that nothing is implemented) and
admonish the user to override these functions in a meaningful way in
order to make use of the pricing methods.

Is there a better way?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,778
Messages
2,569,605
Members
45,238
Latest member
Top CryptoPodcasts

Latest Threads

Top