如何让编译器推导Lambda参数类型并传递泛型Lambda给函数?
问题:让编译器从Lambda推导出参数类型
先看这段编译失败的代码:
#include <iostream> #include <string> struct Bar{ }; struct Foo { template<class T> void setCallback(std::function<void(T)> f) { } }; int main() { Foo foo; foo.setCallback<Bar>([](Bar v) { }); // <--- 编译通过 foo.setCallback([](Bar v) { }); // <--- 编译错误,如何修复? }
编译时会报如下错误:
main.cpp:16:9: error: no matching member function for call to 'setCallback'
foo.setCallback([](Bar v) { }); // <--- 编译错误~~~~~~^
main.cpp:9:10: note: candidate template ignored: could not match 'std::function<void (T)>' against '(lambda at main.cpp:16:21)'
void setCallback(std::function<void(T)> f) {
^
1 error generated.
问题核心:如何让编译器从传入的Lambda推导出其参数类型?
解决方案
通过提取Lambda的operator()成员函数类型,我们可以推导它的参数类型,具体实现代码如下:
template<typename F, typename R, typename E> static E ArgHelper(R(F::*)(E) const); template<typename F, typename R, typename E> static E ArgHelper(R(F::*)(E)); struct Foo { template<class T> void setFunction(T func) { using Arg = decltype(ArgHelper(&T::operator()) ); // 此处可直接使用Arg类型 } }; // 使用示例: foo.setFunction([](Bar b){ //... });
内容的提问来源于stack exchange,提问作者chabapok
相关产品推荐
相关产品推荐

