[英]Passing a function that accepts any number and type of arguments as a class template argument
I am aware that functions can be template arguments. 我知道函数可以是模板参数。 However GCC, Clang and MSVC (compile versions on rextester ) do not compile compile when the template is variadic, as shown below:
但是,当模板为可变参数时,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 produces the most verbose output and possible explanation (rightly or wrongly) as to why the code does not compile. 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
What is the appropriate syntax for passing functions that accept any number of arguments themselves as class template arguments. 对于传递本身接受任意数量的参数作为类模板参数的函数,合适的语法是什么?
Func
is not a type, but a function, Func
不是类型,而是函数,
you might want: 你可能想要:
template struct Bar<decltype(&Func)>;
or maybe 或者可能
template<typename F, F f> struct Bar;
template <typename ...Args, void(*f)(Args...)>
struct Bar<void(*)(Args...), f>
{
};
and Bar<decltype(&Func), &Func>
. 和
Bar<decltype(&Func), &Func>
。
Which can be simplified to (since C++17): 可以简化为(自C ++ 17起):
template <auto> struct Bar;
template <typename ...Args, void(*f)(Args...)>
struct Bar<f>
{
};
and Bar<&Func>
. 和
Bar<&Func>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.