How to implement an easy_bind() that automagically inserts implied placeholders?

后端 未结 2 1572
故里飘歌
故里飘歌 2020-12-05 12:16

I recently found this nifty snippet on the web - it allows you to bind without having to pass in explicit placeholders:

template 

        
2条回答
  •  粉色の甜心
    2020-12-05 13:02

    With the indices trick and the ability to tell std::bind about your own placeholder types, here's what I came up with:

    #include 
    #include 
    #include 
    
    template struct placeholder{};
    
    namespace std{
    template
    struct is_placeholder< ::placeholder> : std::integral_constant{};
    } // std::
    
    namespace detail{
    template
    auto easy_bind(indices, F const& f, Args&&... args)
      -> decltype(std::bind(f, std::forward(args)..., placeholder{}...))
    {
        return std::bind(f, std::forward(args)..., placeholder{}...);
    }
    } // detail::
    
    template
    auto easy_bind(std::function const& f, Args&&... args)
        -> decltype(detail::easy_bind(build_indices{}, f, std::forward(args)...))
    {
        return detail::easy_bind(build_indices{}, f, std::forward(args)...);
    }
    

    Live example.

    Take note that I require the function argument to easy_bind to be either of type std::function, or convertible to it, so that I have a definite signature available.

提交回复
热议问题