[英]Fixed parameters in a function, c++
I am learning C++ and have the following basic question.我正在学习 C++ 并有以下基本问题。 Suppose I define a function taking two arrays as arguments, ie something like
假设我定义了一个 function 以两个 arrays 作为 arguments,即类似
void function1(const real_1d_array &x, const real_1d_array ¶ms)
How can I redefine the function so that I fix the params
to some values and set the function to be only over x
?如何重新定义 function 以便将
params
修复为某些值并将 function 设置为仅超过x
?
You can write an higher order function returning a lambda.您可以编写返回 lambda 的更高阶 function。
#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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.