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
有没有办法让这个推导发生呢?从编译器实现者的角度来看,只要函数参数可以在编译时解析为代码中的函数,技术上似乎是可行的。
如果你想知道背后的动机,请查看此答案下面的评论,特别是
std::bind()
实现的可能优化。编辑:我意识到我可以简单地删除函数参数并使用模板参数,如
templ<func>()
。我添加函数参数的唯一目的是尝试避免传递模板参数。我想要的是,推断出函数指针的类型,例如:
template <typename Function, Function F>
void templ(/* something */);
接着就可以调用
templ(func);
或者
templ<func>();
并且从函数指针的单个提及中推断类型和值。
希望现在更容易理解了。
template<std::size_t N> void foo(std::size_t i) {int arr[N]; /*fill*/ return arr[i];}
。如果我忘记了模板参数,但这个推导是可以完成的,我肯定希望出现错误提示。 - christempl<func>();
不就足够了吗? - christemplate<using typename T, T t>
中的T
,但我认为它没有被采纳。 - christemplate <typename Function> templ(Function func);
有什么问题吗? - Igor Tandetnik