c++ - C++ 17中的拟态std::bind_front用于调用成员函数

标签 c++ c++17 template-meta-programming higher-order-functions bind-front

是否可以在C++ 17中轻松模仿 std::bind_front ? (仅用于成员函数包装就可以了)
我查看了中旨在复制的实现,但实际上它确实非常特定于实现。
我在想一个lambda包装器或模板函数/对象可能起作用?
(这里的性能不是问题)

最佳答案

这可以作为起点

template<typename F, typename ...FrontArgs>
struct bindfronthelper
{
    bindfronthelper(F f, FrontArgs&&...args)
        : mF{std::move(f)}
        , mFrontArg{std::forward<FrontArgs>(args)...}
    {}

    template<typename ...BackArgs>
    auto operator()(BackArgs&&...args) const
    {
        return std::apply(mF, std::tuple_cat(mFrontArg, std::forward_as_tuple(args...)));
    }

    F mF;
    std::tuple<std::decay_t<FrontArgs>...> mFrontArg;
};

template<typename F, typename ...FrontArgs>
auto mybindfront(F f, FrontArgs&&...args)
{
    return bindfronthelper<F, FrontArgs...>{std::move(f), std::forward<FrontArgs>(args)...};
}
https://godbolt.org/z/Tz9fen
写得很快并且测试得不好,因此在极端情况下可能会有一些陷阱。至少它显示了如何实现这一目标。

好吧,我把这个变得复杂了,这是更简单的版本:
template<typename T, typename ...Args>
auto tuple_append(T&& t, Args&&...args)
{
    return std::tuple_cat(
        std::forward<T>(t),
        std::forward_as_tuple(args...)
    );
}

template<typename F, typename ...FrontArgs>
decltype(auto) mybindfront(F&& f, FrontArgs&&...frontArgs)
{
    return [f=std::forward<F>(f), 
            frontArgs = std::make_tuple(std::forward<FrontArgs>(frontArgs)...)]
            (auto&&...backArgs) 
        {
            return std::apply(
                f, 
                tuple_append(
                    frontArgs, 
                    std::forward<decltype(backArgs)>(backArgs)...)); 
        };
}
https://godbolt.org/z/cqPjTY
仍然通过了我提供的所有测试。我保留了旧版本,因为可以进行一些工作使其与旧版本的c++一起使用。

关于c++ - C++ 17中的拟态std::bind_front用于调用成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64712892/

相关文章:

c++ - 当有足够的可用 RAM 时使用交换。性能受影响

c++ - 对于相互转换的类型,有没有办法绕过 "deduced conflicting types for parameter in template instantiation"?

c++ - 在编译时通过 constexpr 或模板函数获取多维 std::array 的大小

c++ - 相同代码执行两次 : performance difference

c++ - 哈希表 - 条件跳转或移动取决于未初始化的值

c++ - 标准库/模板容器的 const 语义的经验法则?

c++ - 将字符串数据附加到 std::vector<std::byte>>

c++ - 连续迭代器检测

c++ - 推导出具有默认模板参数的模板函数指针的模板参数

c++ - 如何为模板类型创建别名?