从可变参数模板调用函子
Call functor from variadic template
是否可以编写可变参数模板类
template<typename Functor, int... D>
struct Foo
{
void bar()
{
// ???
}
};
这相当于
template<typename Functor, int D0>
struct Foo<Functor, D0>
{
void bar()
{
Functor f;
double d0[D0];
f(d0);
}
};
template<typename Functor, int D0, int D1>
struct Foo<Functor, D0, D1>
{
void bar()
{
Functor f;
double d0[D0];
double d1[D1];
f(d0, d1);
}
};
// And so on...
也就是说,要传递给函子的参数数等于模板参数的数量。参数应在堆栈上分配。
在堆栈上带有参数的版本之后通过std::tuple
:
// Helper class to be able to use expansion of std::get<Index>(tuple)
template <int... Is> struct index_sequence {};
// Following create index_sequence<0, 1, 2, .., sizeof...(Is) - 1>
template <int Index, int... Is>
struct make_index_sequence { // recursively build a sequence of indices
typedef typename make_index_sequence<Index - 1, Index -1, Is...>::type type;
};
template <int... Is>
struct make_index_sequence<0, Is...> { // stop the recursion when 0 is reached
typedef index_sequence<Is...> type;
};
template<typename Functor, int... Ds>
struct Foo
{
void bar()
{
bar(typename make_index_sequence<sizeof...(Ds)>::type());
}
private:
template <int... Is>
void bar(index_sequence<Is...>)
{
Functor f;
std::tuple<double[Ds]...> t; // std::tuple<doudle[D0], double[D1], ..>
f(std::get<Is>(t)...); // f(std::get<0>(t), std::get<1>(t), ..);
}
};
这就是你想要的吗?
template<typename Functor, int... D>
struct Foo
{
template<std::size_t N>
std::array<double, N> create()
{
return std::array<double, N>();
}
void bar()
{
Functor f;
f(create<D>()...);
}
};
也许这有效:
template <typename Functor, int i, int... others>
struct Foo
{
template <typename ...T>
void bar(T ... rest)
{
double d[i];
Foo<Functor, others...> foo;
foo.bar(rest..., d);
}
};
template <typename Functor, int i>
struct Foo<Functor, i>
{
template <typename ...T>
void bar(T ... rest)
{
double d[i];
Functor f;
f(d, rest...);
}
};
相关文章:
- 如何链接 DLL 以供 LoadLibrary() 使用(在 Windows 上的 C++ 中)并从调用 exe 导入变
- 调用参数排列不变函数 f(i++, i++)
- 访问并调用 std::function 的变体
- 我可以在输入BSTR变体上调用variantChangeType吗?
- 从C 调用Fortran子例程会产生非法参数值
- 是否有希望在std::变体上高效地调用一个公共基类方法
- 统一处理具有协变类型的函数指针(如何使用派生类型调用回调?
- 从c++调用lua函数时,如何使表和变量值保持不变
- C++构造函数调用变体
- boost变体对通用方法的简单调用
- 如何在c/c++中使函数调用之间的变量值持久化
- 斐波那契汇编x86的一个变体,不得不从c ++主方法调用它,有点丢失在几个部分
- 在调用基类构造函数之前修改构造函数参数值
- 是以前初始化的内存,保证在放置新调用后保持不变
- 注释函数的内容,但保持对函数的调用不变.编译器是否弄清楚不编译函数
- 当用gdb调试我的c++代码时,函数调用中的变量值是荒谬的
- 提升::变体 - "调用没有匹配函数"
- c++11:用向量的元素调用变差函数
- 变量值在没有scanf调用的情况下正在更改
- 调用对象作为默认实参的this