【发布时间】:2020-09-17 22:53:41
【问题描述】:
我有一个名为 FunctionCombiner 的函数(基本类型 ValuationFunction),其中包含其他类似的评估函数:
class FunctionCombiner : public valuationFunction
{
public:
FunctionCombiner(std::vector<std::shared_ptr<valuationFunction>>& Inner_);
void ValueInstrument();
std::vector<std::string> GetuniqueIdentifier() const;
void RiskFactorAdd(double increment, RiskFactor simulatedRiskFactor);
void RiskFactorMultiply(double factor, RiskFactor simulatedRiskFactor);
virtual valuationFunction* clone() const;
private:
std::vector<std::shared_ptr<valuationFunction>> Inner;
};
我需要做的是创建一个函数来返回对这些“内部”函数的引用,但我不确定如何去做,我尝试过的一切似乎在语法上都失败了。如果我只返回一个引用(不在向量内),我会这样处理:
valuationFunction& FunctionCombiner ::GetInner()
{
return *this;
}
我尝试返回类似std::vector< valuationFunction&> 的内容,但编译器似乎不太喜欢这样。解决这个问题的正确方法是什么?
最终目标是收集所有这些对内部函数的引用(来自多个 FunctionCombiners 或不同的评估函数),以便稍后比较它们并整理出重复项。
编辑:从答案中,我现在实现了返回内部引用的函数,如下所示: 对于“内部”类,我的函数现在看起来像这样:
std::vector<std::reference_wrapper<valuationFunction>> StockPriceFunction::GetInnerReference()
{
std::vector<std::reference_wrapper<valuationFunction>> innerVector(1);
innerVector.push_back(std::ref(*this));
return innerVector;
}
对于组合器也是这样:
std::vector<std::reference_wrapper<valuationFunction>> FunctionCombiner::GetInnerReference()
{
std::vector<std::reference_wrapper<valuationFunction>> innerVector(Inner.size());
for (unsigned long i = 0; i < Inner.size(); ++i) {
std::vector<std::reference_wrapper<valuationFunction>> innerInnerVector = Inner[i]->GetInnerReference();
innerVector.insert(innerVector.end(), innerInnerVector.begin(), innerInnerVector.end());
}
return innerVector;
}
但它没有编译并给我奇怪的错误,我在这里做错了什么?
【问题讨论】:
-
您必须使用
std::reference_wrapper。 en.cppreference.com/w/cpp/utility/functional/reference_wrapper -
您不能将引用存储在向量中。您可以获得的最接近的是存储
std::reference_wrappers 或指针(原始或智能指针)。