簡體   English   中英

復制傳遞給模板函數的指針

[英]Make a copy of a pointer passed to template function

我的主要職能有以下幾行。

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

這是有問題的功能。

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;

}

我想將派生類BlackScholesPricer傳遞給該函數,但是我不想修改傳遞給該函數的對象,因此我試圖創建它的副本。 我收到一條錯誤消息,指出不能將BlackScholes *類型的對象轉換為const EuropeanCallOption&(這是我想的復制構造函數)。

解決問題的最有效方法是什么,或者甚至更好的方法是,除了我以外,在這種情況下采取的最佳方法是什么?

由於您正在處理模板函數,因此在着手實現多態克隆方法之前有多種可能:

鑄件

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 ...

}

在參數上使用template參數

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 ...

}

在參數上使用template參數,讓編譯器為您制作副本

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM