如何传播未定义数量的模板参数

How to propagate an undefined number of template arguments?

本文关键字:参数 未定义 何传播 传播      更新时间:2023-10-16

使用以下类,我希望能够创建指定Foo()的实例来存储和调用函数,但是如何将必要的参数传输到函数call

template<class R, class... Args> struct Foo {
    std::function<R(Args...)> func;
    Foo(const std::function<R(Args...)> &funcIn) : func(funcIn) {}
    R call(Args...) {
        return func(/* ? */);
    }
};

例如:

int main() {
    typedef typename Foo<int(int)> Bar;
    Bar x([](int y, int z){return y + z + 2;});
    std::cout << x.call(12, 7);
    return 0;
}

这很简单。只需添加参数名称即可。

R call(Args... args) {
    return func(args...);
}

让它变得简单

R call (Args... as) {
    return func(as...);
}

如果Args...类型是intlongfloat和其他不支持移动语法的简单类型,这应该可以很好地工作。

如果您想添加完美的转发,例如

template <typename ... As>
R call (As && ... as) {
    return func(std::forward<As>(as)...);
}

---编辑---

如果我理解正确(?(根据 Smit Ycyken,这段代码甚至无法编译。

OP 原始代码中有一些错误(class Foo应该是structpublic;main() 中的typedef是错误的(,但以下更正的代码使用我的 g++ 和我的 clang++ 编译

#include <iostream>
#include <functional>
template<class R, class... Args> struct Foo {
    std::function<R(Args...)> func;
    Foo(const std::function<R(Args...)> &funcIn) : func(funcIn) {}
    R call (Args... as) {
       return func(as...);
    }
};
int main ()
 {
   typedef Foo<int, int, int> Bar;
   Bar x([](int y, int z){return y + z + 2;});
   std::cout << x.call(12, 7);
   return 0;
 }