简体   繁体   English

如何在std :: function上创建一个钩子?

[英]How to create a hook on a std::function?

I am trying to figure out how to decorate a std::function with "before" and "after" hooks. 我试图弄清楚如何用“之前”和“之后”钩子装饰std::function

I have some trouble figuring out the right syntax. 我在找出正确的语法时遇到了一些麻烦。 This is what I have so far: 这是我到目前为止:

// create a "before" hook
template<typename Functor, typename Hook>
Functor hook_before(const Functor & original, Hook hook)
{
    // not legal, but illustrates what I want to achieve
    template<typename Args ...args> 
    return [=](Args ...args)
    {
        hook();
        original(args...);
    };
}

My sample application is on Ideone . 我的示例应用程序在Ideone上

Can anyone help me figure it out? 任何人都可以帮我搞清楚吗?

Here goes (untested): 这里(未经测试):

template <typename HOOK, typename RET, typename... ARGS>
struct BeforeHook {
    std::function<RET(ARGS...)> functor;
    HOOK hook;
    BeforeHook(blah) : blah {};

    RET operator()(ARGS&&... args) const {
        hook();
        return functor(args...);
    }
};

template <typename HOOK, typename RET, typename... ARGS>
BeforeHook<HOOK, RET, ARGS...> hook_before(const std::function<RET(ARGS...)> &original, HOOK hook) {
    return BeforeHook<HOOK, RET, ARGS...>(original, hook);
}

Usage: 用法:

auto hooked = hook_before(original_functor, hook_functor);
hooked(args_for_original_functor); // calls hook_functor, then original_functor

Or something along those lines. 或类似的规定。 The original_functor needs to be convertible to std::function , but pretty much everything callable is. original_functor需要可以转换为std::function ,但几乎所有可调用的都是。 Both functors need to be cost-callable, but you could remove the const from operator() if you like. 两个仿函数都需要成本可调,但如果您愿意,可以从operator()删除const

If you want to experiment with returning a lambda rather than an instance of BeforeHook , use the same trick with the template arguments RET and ...ARGS , and find out whether it's possible to use a template argument pack in a lambda: 如果你想尝试返回一个lambda而不是一个BeforeHook的实例,请使用与模板参数RET...ARGS相同的技巧,并找出是否可以在lambda中使用模板参数包:

template <typename HOOK, typename RET, typename... ARGS>
std::function<RET(ARGS...)> hook_before(const std::function<RET(ARGS...)> &original, HOOK hook) {
    return [=](ARGS&&... args) -> RET {
        hook();
        return original(args...);
    };
}

Either way, I think the key trick is using std::function in a template argument deduction to separate the return type from the arguments. 无论哪种方式,我认为关键的技巧是在模板参数推导中使用std::function来将返回类型与参数分开。

You can do it like so: 你可以这样做:

#include <functional>
#include <iostream>

template <class Hook, class ReturnType, class... ArgType>
std::function<ReturnType(ArgType...)> hook_before(
    const std::function<ReturnType(ArgType...)>& original, 
    Hook hook)
{
    return [=](ArgType... args){
        hook();
        return original(std::move(args)...);
    };
}

int main()
{
    std::function<int(int, int)> sum = [](int a, int b) { return a + b; };

    std::cout << sum(3, 4) << std::endl;

    auto myhook = []() { std::cout << "Calculating sum" << std::endl; };
    auto hooked_sum = hook_before(sum, myhook);
    std::cout << hooked_sum(3, 4) << std::endl;
}

The hook_before function accepts two functors, and returns another that accepts the same arguments as the first (the ArgType parameter pack), but calls hook first. hook_before函数接受两个函子,并返回另一个函数接受与第一个函数相同的参数(ArgType参数包),但先调用hook

Try the following. 请尝试以下方法。

template<typename Functor, typename Hook>
struct BeforeHooked
{
    Functor f;
    Hook hook;

    template<class... Args>
    typename std::result_of<F(Args&&...)>::type
    operator()(Args&&... args)
    {
        hook();
        return f(std::forward<Args&&>(args)...);
    }
};

template<typename Functor, typename Hook>
Functor hook_before(Functor f, Hook hook)
{
    return BeforeHooked{f, hook};
}

The code is untested, but assuming you have a compiler which can compile it, I think it should do what you want. 代码是未经测试的,但假设你有一个可以编译它的编译器,我认为它应该做你想要的。 Unlike the other answers, it can accept any functor, not just std::function , and if you give it a polymorphic functor it remains polymorphic. 与其他答案不同,它可以接受任何函子,而不仅仅是std::function ,如果你给它一个多态函子,它仍然是多态的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM