如何包装std :: function并轻松访问其返回值和参数类型?

Jas*_*n R 3 c++ templates variadic-templates template-argument-deduction c++14

我正在尝试做一些简化的事情:

#include <functional>
#include <initializer_list>
#include <vector>

template <typename Ret, typename... Args>
struct func_wrapper
{
public:
    using Func = std::function<Ret(Args...)>;

    Ret operator()(Args && ...args)
    {
        return _impl(std::forward<Args>(args)...);
    }

    void another_function(int another_arg, Args && ...args) { }
    /// and so on

private:
   Func _impl;
};

func_wrapper<void(int, float)> f;


Run Code Online (Sandbox Code Playgroud)

基本上,我想为包装一个类型,std::function并为我的应用程序添加一些其他功能。在我的类型内部,我希望能够在类接口中自由使用返回类型Ret和参数参数包Args。但是,当我尝试使用gcc 8.3编译以上代码时,出现错误

<source>: In instantiation of 'struct func_wrapper<void(int, float)>':
<source>:20:32:   required from here
<source>:9:45: error: function returning a function
     using Func = std::function<Ret(Args...)>;
                                             ^
<source>:11:9: error: function returning a function
     Ret operator()(Args && ...args)
Run Code Online (Sandbox Code Playgroud)

我不确定该怎么做。有一种简单的方法可以做我想要的吗?

tem*_*def 5

@ max66的答案在显示如何避免遇到问题方面做得很好。有关此处特定行不通的详细信息,请查看如何参数化模板以及如何使用它:

template <typename Ret, typename... Args> struct func_wrapper {
     ...
};
Run Code Online (Sandbox Code Playgroud)

这意味着您的模板希望您可以通过编写类似以下内容来实例化它

func_wrapper<int, float> // Function taking a float and returning an int
func_wrapper<void, int, float> // Function taking a float and an int and returning void
func_wrapper<int> // Function taking no arguments and returning void
Run Code Online (Sandbox Code Playgroud)

请特别注意,这func_wrapper<T>意味着Ret它将是T并且该函数将不接受任何参数。

结果,当你写

func_wrapper<void(int, float)>
Run Code Online (Sandbox Code Playgroud)

您说的是“一个表示不带任何参数的函数,并且返回一个带a int和a float并返回的函数void”,这不是您想要的。这就是为什么您会收到有关返回非法函数的错误的原因。