C++ 复制传递给模板函数的指针
我的主要功能中有以下几行C++ 复制传递给模板函数的指针,c++,C++,我的主要功能中有以下几行 BlackScholesPricer* option = new EuropeanCallOption(105, 100, 0.5, 0.1, 0.36, 0); PricingUtil::mesh_pricer<EuropeanCallOption>(option, 105, 150, 5); BlackScholesPricer*期权=新的EuropeanCallOption(105100,0.5,0.1,0.36,0); PricingUtil::m
BlackScholesPricer* option = new EuropeanCallOption(105, 100, 0.5, 0.1, 0.36, 0);
PricingUtil::mesh_pricer<EuropeanCallOption>(option, 105, 150, 5);
BlackScholesPricer*期权=新的EuropeanCallOption(105100,0.5,0.1,0.36,0);
PricingUtil::mesh_pricer(选项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;
}
模板
标准::矢量PricingUtil::网格价格(BlackScholesPricer*选项,
标准::尺寸\u t下限,标准::尺寸\u t上限,标准::尺寸\u t网格大小){
期权类型金融工具(*期权);
标准::向量生成的价格;
对于(std::size\t price=lower\u bound;price,由于您正在处理一个模板函数,因此在匆忙实现多态克隆方法之前,您有几种可能性:
铸造
模板
标准::矢量PricingUtil::网格价格(BlackScholesPricer*选项,
标准::尺寸\u t下限,标准::尺寸\u t上限,标准::尺寸\u t网格大小){
//注意:您似乎确信这是实际类型
期权类型金融工具(*静态投资(期权));
//你的密码在这里。。。
}
在参数上使用模板参数
模板
std::vector PricingUtil::mesh_pricer(选项类型*选项,
标准::尺寸\u t下限,标准::尺寸\u t上限,标准::尺寸\u t网格大小){
期权类型金融工具(*期权);
//你的密码在这里。。。
}
在参数上使用模板参数,并让编译器为您制作副本
模板
std::vector PricingUtil::mesh_pricer(选项类型选项,
标准::尺寸\u t下限,标准::尺寸\u t上限,标准::尺寸\u t网格大小){
//您的代码在这里使用选项安全-它是一个副本。。。
//当然,您需要以稍微不同的方式调用该方法
//以引用而不是指针作为第一个参数
}
注意:复制指针与复制指针指向的对象不同。编写一个虚拟的克隆
函数,让它返回一个副本。然后你可以多态地调用它,并得到正确的结果。BlackScholesPricer
,EuropeanCallOption
之间的关系是什么?@AdamZahranEuropeANCALOPTION
是BlackScholesPricer
的派生类,用于编写自定义副本构造函数,该构造函数将创建对象的深度副本请参见:和
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 <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 <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
}