2

I have the following lines in my main function.

BlackScholesPricer* option = new EuropeanCallOption(105, 100, 0.5, 0.1, 0.36, 0);
PricingUtil::mesh_pricer<EuropeanCallOption>(option, 105, 150, 5);

Here is the function in question.

template <typename OptionType>
std::vector<double> PricingUtil::mesh_pricer(BlackScholesPricer* option, 
std::size_t lower_bound, std::size_t upper_bound, std::size_t mesh_size) {

OptionType financial_instrument(*option);
std::vector<double> generated_prices;

for (std::size_t price = lower_bound; price <= upper_bound; price += mesh_size) {

    financial_instrument.asset_price(price);
    generated_prices.push_back(financial_instrument.price());

}

return generated_prices;

}

I want to pass a derived class BlackScholesPricer to the function but I don't want to modify the object I pass to the function so I'm trying to create a copy of it. I'm getting an error stating that an object of type BlackScholes* cannot be converted to const EuropeanCallOption& (This is from the copy constructor I suppose).

What's the most efficient way of solving the problem, or even better yet, what's the best approach to take in this type of situation other than mine?

Mutating Algorithm
  • 2,604
  • 2
  • 29
  • 66

1 Answers1

5

Since you are dealing with a template function you have several possibilities before you rush to implement a polymorphic clone method:

Casting

template <typename OptionType>
std::vector<double> PricingUtil::mesh_pricer(BlackScholesPricer* option, 
std::size_t lower_bound, std::size_t upper_bound, std::size_t mesh_size) {

    // note: it seems that you are sure that this is the actual type 

    OptionType financial_instrument(*static_cast<OptionType*>(option));

    // your code goes here ...

}

Using the template parameter on your argument

template <typename OptionType>
std::vector<double> PricingUtil::mesh_pricer(OptionType* option, 
std::size_t lower_bound, std::size_t upper_bound, std::size_t mesh_size) {

    OptionType financial_instrument(*option);

    // your code goes here ...

}

Using the template parameter on your argument and let the compiler make the copy for you

template <typename OptionType>
std::vector<double> PricingUtil::mesh_pricer(OptionType option, 
std::size_t lower_bound, std::size_t upper_bound, std::size_t mesh_size) {

    // your code goes here using option safely - it is a copy...
    // of course you need to call the method a bit differently
    // with a reference and not a pointer as first param

}
Amir Kirsh
  • 12,564
  • 41
  • 74
  • 1
    See: https://stackoverflow.com/questions/28002/regular-cast-vs-static-cast-vs-dynamic-cast/1255015#1255015 and https://stackoverflow.com/questions/310451/should-i-use-static-cast-or-reinterpret-cast-when-casting-a-void-to-whatever – Amir Kirsh Jul 16 '19 at 18:37