gpt4 book ai didi

c++ - 函数参数的部分绑定(bind)

转载 作者:IT老高 更新时间:2023-10-28 23:20:35 24 4
gpt4 key购买 nike

有没有办法部分地绑定(bind)可调用对象(例如函数)的第一个/最后一个n个参数而不显式指定其余参数?

std::bind() 似乎要求 all 参数被绑定(bind),那些要留下的应该被绑定(bind)到 std::占位符::_1_2_3

是否可以为从第一个/最后一个参数开始的部分绑定(bind)编写 bind_first()/bind_last() 并自动为任何剩余的未绑定(bind)插入占位符参数在其原始位置中的原始顺序?

最佳答案

Boost 和标准库 bind 都不会自动填空。如果你有一个下雨的晚上,你可以自己写一个这样的小工具;这是一个仅用于普通函数的尾随参数的示例:

#include <tuple>
#include <type_traits>
#include <utility>

template <typename F, typename ...Args> struct trailing_binder;

template <typename R, typename ...Frgs, typename ...Args>
struct trailing_binder<R(Frgs...), Args...>
{
template <typename ...Brgs>
trailing_binder(R (*f)(Frgs...), Brgs &&... brgs)
: the_function(f)
, the_args(std::forward<Brgs>(brgs)...)
{ }

template <unsigned int ...I> struct intlist {};

template <typename ...Brgs>
typename std::enable_if<sizeof...(Brgs) + sizeof...(Args) == sizeof...(Frgs), R>::type
operator()(Brgs &&... brgs)
{
return unwrap(std::integral_constant<bool, 0 == sizeof...(Args)>(),
intlist<>(),
std::forward<Brgs>(brgs)...);
}

private:
template <unsigned int ...I, typename ...Brgs>
R unwrap(std::false_type, intlist<I...>, Brgs &&... brgs)
{
return unwrap(std::integral_constant<bool, sizeof...(I) + 1 == sizeof...(Args)>(),
intlist<I..., sizeof...(I)>(),
std::forward<Brgs>(brgs)...);
}

template <unsigned int ...I, typename ...Brgs>
R unwrap(std::true_type, intlist<I...>, Brgs &&... brgs)
{
return the_function(std::get<I>(the_args)..., std::forward<Brgs>(brgs)...);
}

R (*the_function)(Frgs...);
std::tuple<Args...> the_args;
};

template <typename R, typename ...Args, typename ...Frgs>
trailing_binder<R(Frgs...), Args...> trailing_bind(R (*f)(Frgs...), Args &&... args)
{
return trailing_binder<R(Frgs...), typename std::decay<Args>::type...>(f, std::forward<Args>(args)...);
}

用法:

int f(int a, int b, int c, int d) { return a + b + c + d; }

int main()
{
auto b = trailing_bind(f, 1);
return b(3, 8, 13);
}

关于c++ - 函数参数的部分绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21216762/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com