c++ - 可变参数模板中的函数参数

标签 c++ c++17

是否可以编写一个带有函数作为模板参数的可变参数模板类?

这些是有效的 c++ 声明

template <typename ...Types> class foo;

template <int func(int)>  class bar;

是否可以做类似的事情

template <int func(int)...> class foobar; 

我尝试了很多不同的语法,比如

template <int ...func(int)> class foobar; 

没有编译(我正在使用 gcc 8.1.0 和 -std=c++17)

最佳答案

语法是:

template <int (*...Fs)(int)> class foobar {};

允许

int f1(int);
int f2(int);

foobar<&f1, &f2, &f1> obj;

使用别名可能会帮助您拥有更自然的语法:

using f_int_int = int (*)(int);
template <f_int_int...Fs> class foobar {};

甚至(感谢 Yakk 的评论):

template <typename T> using id_t = T;
template <id_t<int(*)(int)>...Fs> class foobar {};

关于c++ - 可变参数模板中的函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54203728/

相关文章:

c++ - 由于对模板化类型的通用(前向)引用而无法实例化函数模板

c++ - 当没有抛出任何东西时,带有 try-catch 的代码是否仍然很慢

c++ - 为什么 “using namespace std;”被视为不良做法?

c++ - 我有某种薛定谔变量

c++ - 编译时构造函数选择

c++ - 使用任一默认捕获模式时,这是通过复制捕获还是 (*this) 通过引用捕获?是同一回事吗?

c++ - OpenCV C++ Flann IndexParams 和 SearchParams 错误

c++ - 如果构造函数发生异常,如何释放动态内存?

c++ - 编写二进制文件模板函数

c++ - 在 C++ 中使用 s 后缀的任何优势