c – 如何实现自动插入隐含占位符的easy_bind()?

c – 如何实现自动插入隐含占位符的easy_bind()?,第1张

概述我最近在网上找到了这个漂亮的片段 – 它允许你绑定而不必传递明确的占位符: template <typename ReturnType, typename... Args>std::function<ReturnType(Args...)> easy_bind(ReturnType(*MemPtr)(Args...)){ return [=]( Args... args ) -> Ret 我最近在网上找到了这个漂亮的片段 – 它允许你绑定而不必传递明确的占位符:
template <typename ReturnType,typename... Args>std::function<ReturnType(Args...)> easy_bind(ReturnType(*MemPtr)(Args...)){  return [=]( Args... args ) -> ReturnType { return (*MemPtr)( args... ); };}

这个版本很好用没有args:

auto f1 = easy_bind( (std::string(*)(A&,A&))&Worker::MyFn );

后来调用:

std::string s = f1( *p_a1,*p_a2 );

是否可以修改代码以使用最多n个args,用占位符填充2-n(在本例中)?例如,这个应该有一个占位符:

auto f2 = easy_bind( (std::string(*)(A&,A&))&Worker::MyFn,*p_a1 );

后来调用:

std::string s = f2( *p_a2 );

奖金

最终,有这样的东西很好(它不会插入任何占位符,因为它会消耗掉最后一个占位符),但我不认为它对这个实现是可行的(我认为不能模式匹配签名):

auto f3 = easy_bind( f2,*p_a2 );

后来调用:

std::string s = f3();

最重要的是,拥有一个我不需要放在占位符中的bind版本会很好 – 这在通用TMP代码中非常有用.

解决方法 有了 indices trick和 the ability to tell std::bind about your own placeholder types,这就是我想出的:
#include <functional>#include <type_traits>#include <utility>template<int I> struct placeholder{};namespace std{template<int I>struct is_placeholder< ::placeholder<I>> : std::integral_constant<int,I>{};} // std::namespace detail{template<std::size_t... Is,class F,class... Args>auto easy_bind(indices<Is...>,F const& f,Args&&... args)  -> decltype(std::bind(f,std::forward<Args>(args)...,placeholder<Is + 1>{}...)){    return std::bind(f,placeholder<Is + 1>{}...);}} // detail::template<class R,class... FArgs,class... Args>auto easy_bind(std::function<R(FArgs...)> const& f,Args&&... args)    -> decltype(detail::easy_bind(build_indices<sizeof...(FArgs) - sizeof...(Args)>{},f,std::forward<Args>(args)...)){    return detail::easy_bind(build_indices<sizeof...(FArgs) - sizeof...(Args)>{},std::forward<Args>(args)...);}

Live example.

请注意,我要求easy_bind的函数参数为std :: function类型,或者可以转换为它,以便我有一个明确的签名可用.

总结

以上是内存溢出为你收集整理的c – 如何实现自动插入隐含占位符的easy_bind()?全部内容,希望文章能够帮你解决c – 如何实现自动插入隐含占位符的easy_bind()?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1234174.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存