通配符函数指针非类型模板参数
模板可以接受非类型函数指针参数,但是如果接受所有可能的函数指针参数,则会出现问题,例如:
Templates can take non-type function pointer parameters, but there is a problem if all possible function pointer parameters are accepted, example:
void dummy()
{
}
template <typename FT, FT* fp>
void proxy()
{
fp();
}
int main()
{
proxy<decltype(dummy), &dummy>();
return 0;
}
正如你所看到的,这很麻烦。是否存在更方便的方法来提供通配符函数指针作为非类型模板参数?
As you can see, this is very cumbersome. Does there exist a more convenient way to provide a "wildcard" function pointer as a non-type template parameter?
解决方案你的特定问题将是简单地只需要作为一个模板参数和项作为一个普通的函数参数的函数类型。您也可以使用类型推导,而不是明确指定使用哪些参数类型:
A better solution for your particular problem would be to simply take only the function type as a template argument and the item as an ordinary function argument. You can also use type deduction instead of explicitly specifying which argument types are used:
void dummy()
{
}
template <typename FT>
void proxy(FT fp)
{
fp();
}
int main()
{
proxy(fp);
return 0;
}