如何传播未定义数量的模板参数
How to propagate an undefined number of template arguments?
使用以下类,我希望能够创建指定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...
类型是int
、long
、float
和其他不支持移动语法的简单类型,这应该可以很好地工作。
如果您想添加完美的转发,例如
template <typename ... As>
R call (As && ... as) {
return func(std::forward<As>(as)...);
}
---编辑---
如果我理解正确(?(根据 Smit Ycyken,这段代码甚至无法编译。
OP 原始代码中有一些错误(class Foo
应该是struct
或public
;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;
}
相关文章:
- 为什么当函数参数未定义为常量引用时存在无限递归?
- 未优化的 constexpr 的未定义引用用作默认参数
- 当通过引用传递 QObject 时,C++信号的参数在 QML 中显示为"未定义"
- 如何传播未定义数量的模板参数
- 编译后未定义的宏参数会发生什么
- 如何将一个或多个(未定义的数字)参数传递给函数
- 将未定义的参数计数作为模板参数的函数指针
- 函数参数中未声明和未定义的标识符
- 我的参数化构造函数说我的字符串变量未定义
- 可变参数模板数组调用未定义的行为
- 基类的未定义模板参数
- 谷歌测试框架允许未定义的参数进行测试
- 对参数的构造函数的未定义引用
- 为什么if语句中未定义的参数不会导致segfault或其他错误
- 具有未定义参数的私有副本构造函数
- 类型为"double"的输入参数的未定义函数
- 对具有相同参数的成员函数的未定义引用
- C++ 将参数数量未定义的函数传递给类
- 对"pthread_key_create"的未定义引用;参数顺序不能解决问题
- C++:自定义rand_int函数的参数未初始化