函数作为可变参数模板的参数

时间:2014-10-09 08:30:33

标签: c++ templates variadic-templates

假设我们有一个班级

template <int(*F)(int, int)>
class A {
    // ...
};

它需要一个函数作为模板参数。

现在我想制作一个可变参数模板,它将函数作为模板参数。

template <int(*F...)(int, int)> // this won't compile
template <int(*F)(int, int)...> // this won't compile either

如何正确地做到这一点?

4 个答案:

答案 0 :(得分:18)

你可以做

using Function_t = int(*)(int, int);

template <Function_t ... Fs> struct s{};

否则,如果您不想使用typedef

template <int(*...Fs)(int, int)> struct s{};

注意:第二个版本不能是匿名的(Fs是必需的)因为ISO C ++ 11要求带括号的包声明具有名称。

答案 1 :(得分:12)

template <int(*...F)(int, int)>
class A {
    // ...
};

答案 2 :(得分:3)

只需使用F作为模板参数。 这不仅允许您使用函数作为参数,还允许使用实现括号运算符的其他类型。 这些类称为仿函数

答案 3 :(得分:2)

函数指针类型语法很烦人。所以围绕它编码:

template<class T> using type=T;

template< type<int(int,int)>* ... Fs >
class A {
};