微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将任何 lambda 函数包括捕获 lambdas转换为 std::function 对象的模板 简单的案例更棘手的情况

如何解决将任何 lambda 函数包括捕获 lambdas转换为 std::function 对象的模板 简单的案例更棘手的情况

我有以下代码可以将 lambda 转换为 C 风格的函数指针。这适用于所有 lambda,包括带捕获的 lambda。

#include <iostream>
#include <type_traits>
#include <utility>

template <typename Lambda>
struct lambda_traits : lambda_traits<decltype(&Lambda::operator())>
{};

template <typename Lambda,typename Return,typename... Args>
struct lambda_traits<Return(Lambda::*)(Args...)> : lambda_traits<Return(Lambda::*)(Args...) const>
{};

template <typename Lambda,typename... Args>
struct lambda_traits<Return(Lambda::*)(Args...) const>
{
    using pointer = typename std::add_pointer<Return(Args...)>::type;

    static pointer to_pointer(Lambda&& lambda)
    {
        static Lambda static_lambda = std::forward<Lambda>(lambda);
        return [](Args... args){
            return static_lambda(std::forward<Args>(args)...);
        };
    }
};

template <typename Lambda>
inline typename lambda_traits<Lambda>::pointer to_pointer(Lambda&& lambda)
{
    return lambda_traits<Lambda>::to_pointer(std::forward<Lambda>(lambda));
}

这可用于将带有捕获的 lambda 传递到 C 风格的 API 中:


// Function that takes a C-style function pointer as an argument
void call_function(void(*function)())
{
    (*function)();
}

int main()
{
    int x = 42;

    // Pass the lambda to the C-style API
    // This works even though the lambda captures 'x'!
    call_function(to_pointer([x] {
        std::cout << x << std::endl;
        }));
}

鉴于此,编写一个类似的模板似乎应该相对简单,可以将 lambdas(包括带捕获的 lambdas)一般转换为 std::function 对象,但我正在努力弄清楚如何。 (我对模板元编程技术不是很熟悉,所以我有点迷茫)

这是我尝试过的,但无法编译:

template <typename Lambda>
struct lambda_traits : lambda_traits<decltype(&Lambda::operator())>
{};

template <typename Lambda,typename... Args>
struct lambda_traits<typename std::function<Return(Args...)>> : lambda_traits<typename std::function<Return(Args...)> const>
{};

template <typename Lambda,typename... Args>
struct lambda_traits<typename std::function<Return(Args...)> const>
{
    using pointer = typename std::function<Return(Args...)>*;

    static pointer to_pointer(Lambda&& lambda)
    {
        static Lambda static_lambda = std::forward<Lambda>(lambda);
        return [](Args... args) {
            return static_lambda(std::forward<Args>(args)...);
        };
    }
};

template <typename Lambda>
inline typename lambda_traits<Lambda>::pointer to_pointer(Lambda&& lambda)
{
    return lambda_traits<Lambda>::to_pointer(std::forward<Lambda>(lambda));
}

这无法编译并表示 Lambda 模板参数未被部分特化使用。

这样做的正确方法是什么?

(注意,我一直在使用兼容 C++11 的编译器,因此无法使用 C++14 及更高版本的功能

解决方法

如果您想在不指定 std::function 签名的情况下将可调用对象转换为 std::function,这正是 C++17's deduction guides for std::function 的用途。我们只需要为 C++11 实现一个版本。请注意,这仅适用于具有非重载 operator() 的可调用对象;否则,没有办法做到这一点。

#include <functional>
#include <utility> // std::declval

// Using these functions just for the return types,so they don't need an implementation.

// Support function pointers
template <typename R,typename... ArgTypes>
auto deduce_std_function(R(*)(ArgTypes...)) -> std::function<R(ArgTypes...)>;

// Support callables (note the _impl on the name).
// Many overloads of this to support different const qualifiers and
// ref qualifiers. Technically should also support volatile,but that
// doubles the number of overloads and isn't needed for this illustration.
template <typename F,typename R,typename... ArgTypes>
auto deduce_std_function_impl(R(F::*)(ArgTypes...)) -> std::function<R(ArgTypes...)>;

template <typename F,typename... ArgTypes>
auto deduce_std_function_impl(R(F::*)(ArgTypes...) const) -> std::function<R(ArgTypes...)>;

template <typename F,typename... ArgTypes>
auto deduce_std_function_impl(R(F::*)(ArgTypes...) &) -> std::function<R(ArgTypes...)>;

template <typename F,typename... ArgTypes>
auto deduce_std_function_impl(R(F::*)(ArgTypes...) const&) -> std::function<R(ArgTypes...)>;

template <typename F,typename... ArgTypes>
auto deduce_std_function_impl(R(F::*)(ArgTypes...) &&) -> std::function<R(ArgTypes...)>;

template <typename F,typename... ArgTypes>
auto deduce_std_function_impl(R(F::*)(ArgTypes...) const&&) -> std::function<R(ArgTypes...)>;

// To deduce the function type for a callable,get its operator() and pass that to
// the _impl functions above.
template <typename Function>
auto deduce_std_function(Function)
    -> decltype(deduce_std_function_impl(&Function::operator()));

template <typename Function>
using deduce_std_function_t = decltype(deduce_std_function(std::declval<Function>()));

template <typename F>
auto to_std_function(F&& fn) -> deduce_std_function_t<F> {
    return deduce_std_function_t<F>(std::forward<F>(fn));
}

Demo


更详细的解释

我们需要推导出 std::function<...> 的函数类型。所以我们需要实现某种deduce_std_function来确定函数类型。实现这一点有多种选择:

  • 制作一个 function_traits 类型,为我们找出函数类型(类似于您的 lambda_traits)。
  • deduce_std_function 实现为重载集,其中重载的返回类型是推导的类型。

我选择后者是因为它模仿了演绎指南。前者也可以,但我认为这种方法可能更容易(函数样板比结构样板小)。

简单的案例

查看 std::function 的演绎指南的文档,有一个简单的:

template<class R,class... ArgTypes>
function(R(*)(ArgTypes...)) -> function<R(ArgTypes...)>;

这很容易翻译:

template <typename R,typename... ArgTypes>
auto deduce_std_function(R(*)(ArgTypes...)) -> std::function<R(ArgTypes...)>;

基本上,给定任何函数指针 R(*)(ArgTypes...),我们想要的类型是 std::function<R(ArgTypes...)>

更棘手的情况

文档将第二种情况描述为:

此重载仅在以下情况下参与重载决议 &F::operator() 在被视为未计算的操作数时是良构的 和 decltype(&F::operator()) 的形式为 R(G::*)(A...)(可选 cv 限定,可选 noexcept,可选左值引用 限定)对于某些类类型 G。推导出的类型是 std::function<R(A...)>

那是一口。然而,这里的关键思想是碎片:

  • "decltype(&F::operator()) 的形式为 R(G::*)(A...)"
  • "推导出的类型是std::function<R(A...)>"

这意味着我们需要获取 operator() 的成员函数指针,并使用该成员函数指针的签名作为 std::function 的签名。>

这就是它的来源:

template <typename Function>
auto deduce_std_function(Function)
    -> decltype(deduce_std_function_impl(&Function::operator()));

我们委托给 deduce_std_function_impl,因为我们需要推导出指向成员函数的指针 &Function::operator() 的签名。

该 impl 函数的有趣重载是:

template <typename F,typename... ArgTypes>
auto deduce_std_function_impl(R(F::*)(ArgTypes...)) -> std::function<R(ArgTypes...)>;

简而言之,我们正在获取指向成员函数的指针的签名(R ... (ArgTypes...) 位)并将其用于 std::function。语法的其余部分((F::*) 位)只是指向成员函数的指针的语法。 R(F::*)(ArgTypes...) 是类 F 的成员函数指针类型,签名为 R(ArgTypes...),没有 const、volatile 或引用限定符。

等等!我们希望支持 const 和引用限定符(您也可能希望添加对 volatile 的支持)。所以我们需要复制上面的 deduce_std_function_impl,为每个限定符复制一次:

签名 类声明
R(F::*)(ArgTypes...) void operator()();
R(F::*)(ArgTypes...) const void operator()() const;
R(F::*)(ArgTypes...) & void operator()() &;
R(F::*)(ArgTypes...) const& void operator()() const&;
R(F::*)(ArgTypes...) && void operator()() &&;
R(F::*)(ArgTypes...) const&& void operator()() const&&;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。