c++模板包的函数参数

C++ template pack for function argument

本文关键字:函数 参数 c++      更新时间:2023-10-16

是否可以创建一个接收函数指针可变参数包的模板函数?

template<ReturnType (*FN)(), ReturnType (*FNX...)()>
void run() {
  ...
  run<FNX...>();
  ...
}

我试着把...放在我能想到的所有地方,但我不能让它编译。不支持这个吗?

您可以使用这种语法,但是它看起来真的很奇怪:

template<void(*... Functions)()>
void call_all()
{
    initializer_list<int>{(Functions(), 0)...};
}

我要别名类型,不过:

template <typename T>
using function_ptr = add_pointer_t<enable_if_t<is_function<T>::value,T>>;
template<function_ptr<void()>... Functions>
void call_all()
{
    initializer_list<int>{(Functions(), 0)...};
}

你也可以使用辅助类来做更高级的处理:

using fp = function_ptr<string()>;
template<fp First, fp... Others>
struct helper
{
    static void run()
    {
        helper<First>::run();
        helper<Others...>::run();
    }
};
template<fp One>
struct helper<One>
{
    static void run()
    {
        DBG(One());
    }
};
template<fp... Functions>
void run()
{
    helper<Functions...>::run();
}

现场演示