![](/img/trans.png)
[英]How can I use templates here to avoid using std::function in this code
[英]How to use templates to avoid using std::function
我有一個 class 描述了某種類型的 function (這里我的意思是 function 在數學上,而不是編程意義上)。 在這個 class 中,我有一個名為 integration(...) 的方法,它使用 std::function 和 std::string 來確定要做什么。 我知道我做事的方式很糟糕,我想要一些關於如何更好地編碼的想法。 最好我想避免使用 std::function 而是使用模板。 下面是我所擁有的顯示基本思想的簡化。
我也不認為我所擁有的效率很高。 集成方法可能非常昂貴並且被多次調用,因此提高效率會很有幫助。
class SomeFunction
{
public:
SomeFunction(SomeParameter param) { // do constructor type things // }
double value(double coord) { // return the value of the function // }
double derivative(double coord) { // return the derivative of the function // }
double integrate(std::string case, SomeType domain_of_integration)
{
std::function<double(double)> to_be_integrated;
double some_other_parameter;
if (case == "value") {
to_be_integrated = [&](double x) -> double {
return this->value(x);
};
some_other_parameter = foo;
}
else if (case == "derivative") {
to_be_integrated = [&](double x) -> double {
return this->derivative(x);
};
some_other_parameter = bar;
}
else {
std::cerr << "ERROR - invalid integral\n";
exit(1);
}
// evaluate the integral using
// to_be_integrated, some_other_parameter and domain_of_integration
}
private:
// some member variables //
};
用模板參數替換std::function
很容易,例如
class SomeFunction
{
template <typename I>
double do_integration(I&& integrand, double param, SomeType domain)
{
// evaluate the integral using
// integrand(x), param and domain
}
public:
// ...
double integrate(std::string case, SomeType domain)
{
if (case == "value") {
return do_integration(
[&](double x) -> double {
return this->value(x);
},
foo, domain);
}
else if (case == "derivative") {
return do_integration(
[&](double x) -> double {
return this->derivative(x);
},
bar, domain);
}
else {
std::cerr << "ERROR - invalid integral\n";
exit(1);
}
}
};
但是這是否真的會表現得更好,很難單獨說。 您需要使用實際功能對兩個版本進行概要分析才能有任何信心。
我知道我做事的方式很差...不要認為我所擁有的很有效...集成方法可能會非常昂貴...
這些都是非常模糊的——每個人都對他們期望的快或慢有這些感覺,但如果它足夠重要以至於值得優化,那么它就足夠重要了,值得首先進行分析。
我已經看到很多看起來很慢但足夠快的代碼,以及像上面這樣的幾個內聯優化,它們通過影響指令緩存使事情變慢。
通常我會建議在進行任何更改之前進行測量,以確保它可以很好地利用時間 - 因為這是一個簡單的更改(一旦你認識到它),在這種情況下測量兩者是合理的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.