简体   繁体   中英

Fixed parameters in a function, c++

I am learning C++ and have the following basic question. Suppose I define a function taking two arrays as arguments, ie something like

void  function1(const real_1d_array &x, const real_1d_array &params)

How can I redefine the function so that I fix the params to some values and set the function to be only over x ?

You can write an higher order function returning a 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM