相关疑难解决方法(0)

有没有办法推断出函数指针模板参数的值?

C++允许非类型模板参数为指针,包括函数指针,类型.最近,我问了一个问题,什么这是有用的,这是一个后续行动的答案之一.

从作为函数指针的函数参数中推导出函数指针模板参数的是否可行?例如:

using VoidFunction = void(*)();

template <VoidFunction F>
void templ(VoidFunction);

...

void func();  // a VoidFunction

...

templ<func>(func);  // works, but I have to specify the template parameter explicitly
templ(func);        //  <-- I would like to be able to do this
Run Code Online (Sandbox Code Playgroud)

有没有办法让这种演绎发生?从编译器实现者的角度来看,技术上似乎是可能的,只要函数参数可以在编译时解析为代码中的函数.

如果您想知道这背后的动机,请参阅此答案下的评论,特别是可能的实施优化std::bind().

编辑:我意识到我可以简单地删除函数参数并使用模板参数,如templ<func>().添加函数参数的唯一目的是尽量避免传递模板参数.

我想我真正想要的是,还推断出函数指针的类型,如:

template <typename Function, Function F>
void templ(/* something */);
Run Code Online (Sandbox Code Playgroud)

然后就可以打电话了

templ(func);
Run Code Online (Sandbox Code Playgroud)

要么

templ<func>();
Run Code Online (Sandbox Code Playgroud)

并且只需提及函数指针就可以推导出类型和值.

希望现在更有意义.

c++ templates non-type template-argument-deduction

6
推荐指数
1
解决办法
977
查看次数