我知道函数可以是模板参数。但是 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/