给定boost::bind
或 std::
等价物,我可以这样做:
int f(int a, int b)
{
return a + b;
}
auto f_two = boost::bind(f, 1, 1);
因此 f_two()
将通过有效地调用中间函数返回 2,该中间函数通过任何实现机制调用 f(1, 1)
,也许类似于:
double f_two_caller()
{
return f(stored_arg_1, stored_arg_2);
}
但是,我的用例是我想绑定(bind)一个前缀函数,所以我可以说:
auto f_print = boost::bind(printf, "Hello, world!\n");
auto f_print_and_two = boost::bind_with_prefix(f, f_print, 1, 1);
所以 f_print_and_two()
有效地执行:
double f_print_and_two_caller()
{
f_print(f_print.stored_arg_1);
return f(stored_arg_1, stored_arg_2);
}
我确定该技术有一个合适的名称,我可以用它来查找解决方案,但我现在想不出...
最佳答案
template<class First, class Second>
struct compose_t {
First first;
Second second;
template<class...Args>
auto operator()(Args&&...args)
-> decltype( std::declval<Second&>()( std::declval<First&>()( std::declval<Args>()... ) ) )
{ return second(first( std::forward<Args>(args)... ) ); }
};
template<class First, class Second>
compose_t<typename std::decay<First>::type, typename std::decay<Second>::type>
compose( First&& first, Second&& second ){ return {std::forward<First>(first), std::forward<Second>(second)}; }
这是函数式组合。
auto f_print = std::bind(printf, "Hello, world!\n");
auto f_print_and_two = std::bind( compose(f, f_print), 1, 1 );
int main() {
f_print_and_two();
}
和done .
请注意,函数组合可以链接。您甚至可以根据上述内容编写一个可变的 compose
函数。
关于c++ - boost::bind()-类似的东西,但用于函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52773022/