簡體   English   中英

boost :: bind()類似,但用於函數調用

[英]boost::bind()-like thing, but for function calls

給定boost::bindstd::等價物,我可以做到:

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

auto f_two = boost::bind(f, 1, 1);

這樣, f_two()將通過有效的調用通過任何實現機制調用f(1, 1)的中間函數來返回2,也許是這樣的:

double f_two_caller()
{
     return f(stored_arg_1, stored_arg_2);
}

但是,我的用例是我想綁定一個前綴函數,所以我可以說:

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);
}

我確定可以使用這種技術來查找解決方案,但是我現在想不起來...

我認為從您的描述中,您正在尋找的是:

#include <cstdio>
#include <tuple>
#include <utility>
#include <functional>

template<class F, class PrefixF, class...Args>
auto wrap_call_prefix(F&& f, PrefixF&& pf, Args&&...args)
{
    return [f = std::forward<F>(f), 
            pf = std::forward<PrefixF>(pf),
            args = std::make_tuple(std::forward<Args>(args)...)]
            {
                pf();
                return std::apply(f, args);
            };
}

int main()
{
    auto add = [](auto x, auto y) { return x + y; };
    auto f_print = std::bind(printf, "Hello, world!\n");

    auto f_print_and_two_caller = wrap_call_prefix(add, f_print, 1, 2);

    printf("%d\n", f_print_and_two_caller());
}

std::apply是c ++ 17。

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();
}

完成

請注意,功能組合可以鏈接。 您甚至可以根據上述內容編寫可變的compose函數。

如果我是你,我將不會復制bind功能,而只會進行類似以下的操作,這很簡單:

template<class Pre, class U>
class with_prefix_class{
public:
    template<class V, class W>
    with_prefix_class(V &&v, W &&w) : pre_(std::forward<V>(v)), func_(std::forward<W>(w)){}

    decltype(std::declval<U>()()) operator()(){
        pre_();
        return func_();
    }

private:
    Pre pre_;
    U func_;
};

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

template<class Pre, class U>
with_prefix_class<Pre, U> with_prefix(Pre &&pre, U &&u){
    return with_prefix_class<Pre, U>(std::forward<Pre>(pre), std::forward<U>(u));
}

int main(int argc, char* argv[]) {
    auto a = with_prefix([](){}, std::bind(f, 5, 3));
    a();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM