首页 文章

c 11 - 将result_of,decltype,std :: function和variadic模板一起工作

提问于
浏览
2

我在使用std :: result_of,decltype和std :: function方面遇到了麻烦

使用可变参数模板 .

我有以下功能 -

int foo(int a, int b, int c) {
    std::cout << a << b << c << std::endl;
    return 0;
}

以下课程

template <class T, class... Args>
class VariadicTest {
public:
    VariadicTest(const T& func, Args... args) : func(func) {};
private:
    T func;
};

我希望在类中有一个成员来保存lambda表达式,

为此我需要一个std :: function .

我的问题是如何正确定义std :: function .

这个类的用例看起来像 -

VariadicTest(foo, 1,2,3);

所以现在我有T = int __cdecl(int,int,int)和Args =(int - 1,int - 2,int - 3)

从这里我想要一个看起来像这样的成员函数:

std::function<std::result_of<T(Args...)::type(Args...)>

现在这当然没有编译,也没有50个左右我试过的其他东西 .

基本上我需要这个例子以下声明

std::function<int(int,int,int)> _f;

当然,根据给定的T和Args,这是自动化的 .

1 回答

  • 4

    请尝试以下方法:

    template <class T, class... Args>
    class VariadicTest {
    public:
        VariadicTest(const T& func, Args... args) : func(std::bind(func, args...)) {};
    private:
        using result_type_t = typename std::result_of<T(Args...)>::type;
        std::function<result_type_t()> func;
    };
    

相关问题