c++ - 传递接受任意数量和类型参数的函数作为类模板参数

标签 c++ variadic-templates

我知道函数可以是模板参数。但是 GCC、Clang 和 MSVC(在 rextester 上编译版本)在模板可变时不编译编译,如下所示:

void Func( int ){}

template<void (*)(int)>
struct Foo{};

template struct Foo<Func>; // Compiles

template<typename>
struct Bar;

template<typename ...Args>
struct Bar<void(*)(Args...)>
{
};

template struct Bar<Func>; // Does NOT compile (why???)

int main()
{
}

MSVC 产生最详细的输出和可能的解释(正确或错误)为什么代码不能编译。

source_file.cpp(20): error C2923: 'Bar': 'Func' is not a valid template type argument for parameter 'T'
source_file.cpp(1): note: see declaration of 'Func'
source_file.cpp(20): error C2990: 'Bar': non-class template has already been declared as a class template
source_file.cpp(13): note: see declaration of 'Bar'
source_file.cpp(20): error C2946: explicit instantiation; 'Bar' is not a template-class specialization  

传递函数的适当语法是什么,这些函数本身接受任意数量的参数作为类模板参数。

最佳答案

Func不是类型,而是函数,

你可能想要:

template struct Bar<decltype(&Func)>;

或者也许

template<typename F, F f> struct Bar;

template <typename ...Args, void(*f)(Args...)>
struct Bar<void(*)(Args...), f>
{
};

Bar<decltype(&Func), &Func> .

可以简化为(C++17 起):

template <auto> struct Bar;

template <typename ...Args, void(*f)(Args...)>
struct Bar<f>
{
};

Bar<&Func> .

关于c++ - 传递接受任意数量和类型参数的函数作为类模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52164032/

相关文章:

c++ - 无法初始化静态 QList?

C++虚函数覆盖

c++ - 检索元素

c++ - 如何使用带有可变参数的动态转换?

c++ - 从参数包创建索引和类型对

c++类只能通过引用传递

c++ - 将 OpenCV 原始指针和 lambda 用于直方图的不同结果

c++ - 为什么不会在函数调用中将模板形参包推导出为多个类型实参?

c++ - 用于默认模板参数的参数包

c++ - C++:使用参数包显式调用函数重载