【问题标题】:Is there a way to convert a function pointer to an std::function without specifying return type and argument type?有没有办法在不指定返回类型和参数类型的情况下将函数指针转换为 std::function?
【发布时间】:2022-01-14 18:11:37
【问题描述】:

我有一个函数指针,我需要将它传递给一个需要 std::function 的函数。接受std::function 的函数是模板化的,并使用std::function 的参数来推导出参数包,这意味着隐式转换将不起作用。

我可以自己构造std::function,但是传递的函数有很多参数,并且将它们写入std::function 的模板括号将是不可持续的,因为我需要经常使用许多类似的函数来执行此操作,我传递给这个函数。

有没有办法通过某种形式的推导将函数指针转换为std::function 而无需指定返回类型和参数?

这是我迄今为止尝试过的:

template <auto* F>
struct stdfunc {};

template <class Ret, class... Args, auto (*F)(Args...) -> Ret>
struct stdfunc<F>
{
    typedef std::function<Ret(Args...)> type;
};

上面的代码没有按预期工作。我在this answer 中找到了语法。在那种情况下,它没有用于此目的,但肯定有一种方法可以使用这种技术来实现我想要做的事情吗?似乎所有的碎片都在那里,我只需要把它们放在正确的地方。

我走对了吗?

【问题讨论】:

    标签: c++ function templates


    【解决方案1】:

    我建议:

    template<typename Func>
    auto make_function(Func ptr)
    {
        return std::function<std::remove_pointer_t<Func>>(ptr);
    }
    

    然后简单地传递“make_function(my_func)”。

    (感谢 Remy Lebeau 建议使用“auto”)

    【讨论】:

    • 让函数返回auto不是更简单吗? template&lt;typename Func&gt; auto make_function(Func ptr) { return std::function&lt;std::remove_pointer_t&lt;Func&gt;&gt;(ptr); }
    • 完美!有没有办法在编译时检查 Func 是否为函数指针类型?使用static_assertenable_if
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-07
    • 2018-02-01
    • 1970-01-01
    • 2016-02-25
    • 1970-01-01
    • 1970-01-01
    • 2014-01-17
    相关资源
    最近更新 更多