函数中的固定参数,c++; 我学习C++,有以下基本问题。假设我定义了一个以两个数组作为参数的函数,例如 void function1(const real_1d_array &x, const real_1d_array ¶ms)
如何重新定义函数,以便将函数中的固定参数,c++; 我学习C++,有以下基本问题。假设我定义了一个以两个数组作为参数的函数,例如 void function1(const real_1d_array &x, const real_1d_array ¶ms),c++,function,C++,Function,如何重新定义函数,以便将参数固定为某些值,并将函数设置为仅在x上?您可以编写一个返回lambda的高阶函数 #include <iostream> // Original function template< class X, class P > void func_impl(X const& x, P const& param) { std::cout << (x + params) << '\n'; // What
参数固定为某些值,并将函数设置为仅在x
上?您可以编写一个返回lambda的高阶函数
#include <iostream>
// Original function
template< class X, class P >
void func_impl(X const& x, P const& param)
{
std::cout << (x + params) << '\n'; // Whatever...
}
// The returned lambda embeds the parameter
template< class P >
auto make_func(P const& param)
{
return [p = param] (auto x) {
func_impl(x, p);
};
}
int main()
{
auto f{ make_func(42) };
f(17);
}
#包括
//原函数
模板
无效函数impl(X常量和X,P常量和参数)
{
std::cout default parameter或重载或std::bind
或lambda。您所说的修复参数是什么意思?如果您总是想要某个参数,那么就不要将其设置为参数,而改为局部变量。不确定您真正想要做什么。@Devolus参数稍后会在代码中更改。但是,我需要传递一个对于一个优化器,它只超过x。例如,在Matlab中,这可以使用函数句柄@(x)来完成。