【问题标题】:VS2012 complains when using +[]{} sorceryVS2012 使用 +[]{} 巫术时报错
【发布时间】: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


【解决方案1】:

这与this bug 相关(按“设计”关闭)。 VC++ 支持 x86 上的多个调用约定,并且带有空捕获列表的 lambda 提供对它们的转换。这就是为什么会有歧义。

很遗憾,没有列出您尚未尝试过的解决方法。

顺便说一下,这个错误在Visual C++ 2015 Update 2中被列为已修复

【讨论】:

  • 我安装了 Visual Studio Community 2015 Version 14.0.25431.01 Update 3 现在不仅是 IDE,而且编译器也抱怨:/
  • @testman 我记得有一个与 Visual Studio 2015 的命名混淆,两个版本的命名非常相似,是不同的东西:pay.reddit.com/r/cpp/comments/56ecje/…也许你是那个的受害者?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-31
  • 1970-01-01
相关资源
最近更新 更多