【发布时间】:2016-11-06 20:42:20
【问题描述】:
我希望在使用 lambda 时自动推导接受函数的模板化函数的参数。这个例子展示了我的一些选择:
template <class T>
void foo(void (*func)(T)) {
T val;
// do something with val and func...
}
int main() {
auto pfunc0 = [] (int) { /*...*/ };
void (*pfunc1)(int) = [] (int) { /*...*/ };
auto* pfunc2 = +[] (int) { /*...*/ };
foo(pfunc0); // not ok
foo<int>(pfunc0); // ok, but redundant
foo(pfunc1); // ok, but redundant
foo(pfunc2); // ok
}
pfunc2 使用了我在这里学到的技巧:Obtaining function pointer to lambda?。所以实际上我应该对 pfunc2 案例感到满意,因为它是简洁且不重复的代码,不幸的是,Visual C++ 2012 IDE 抱怨它是错误的代码,即使它编译得很好。
是否有针对此问题的解决方法或建议?
IDE 错误消息:
在“auto* pfunc2”行中:IDE 在“auto”下划线并说
Error: cannot deduce 'auto' type
它还在抱怨的地方加下划线'['
Error: more than one conversion function from "lambda[]void (int)->void" to a build-in type applies: function "lambda[]void (int)->void::operator void (*)(int)() const" function "lambda[]void (int)->void::operator void (*)(int)() const" function "lambda[]void (int)->void::operator void (*)(int)() const"
【问题讨论】:
-
我无权访问VS2012,但是你试过
foo(+pfunc0);吗? -
@krzaq 我用错误消息更新了我的问题。我尝试了您的建议,但它没有改变任何东西(相同的错误消息)。
-
@testman 我的错,我完全错过了!
-
@Quentin 我用错误消息的图片更新了我的问题。
-
@krzaq 我阅读了您现在已删除的答案,假设没有解决方法,是否可以忽略 IDE 抱怨或不鼓励?如果确实有问题,我总是可以使用更详细的代码。
标签: c++11 templates visual-studio-2012 lambda