带有未定义参数的函数指针计数作为模板参数

时间:2018-01-22 22:06:25

标签: c++ c++11 templates variadic-templates

我正在寻找一种方法来传递一个带有未定义参数计数和类型作为模板参数的函数指针。

在我的研究中,我已经找到this

STC<void (*)()> s(foo2, fp); // like this

所以看起来通常可以将函数指针作为模板参数传递。我现在的问题是,如果有可能做这样的事情

STC<void (*)(T&&... t)> s(foo2, fp);

其他信息: 我想传递函数指针的类应该只包含数组中的函数列表,并且没有其他函数。

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您正在寻找部分专业化。

我的意思是(感谢Jarod42的改进)

template <typename>
struct foo;

template <typename ... Ts>
struct foo<void(*)(Ts ...)>
 { void(*ptr)(Ts ...); };

但是观察模板参数不是函数指针;是函数指针的类型。

以下是一个完整的工作示例

#include <iostream>

template <typename>
struct foo;

template <typename ... Ts>
struct foo<void(*)(Ts ...)>
 { void(*ptr)(Ts ...); };

void func1 ()
 { std::cout << "func1" << std::endl; }

void func2 (int, long)
 { std::cout << "func2" << std::endl; }


int main ()
 {
   foo<decltype(&func1)>  f1 { &func1 };
   foo<decltype(&func2)>  f2 { &func2 };

   f1.ptr();
   f2.ptr(1, 2L);
 }